在大型应用开发的时候,页面可以划分成很多部分。往往不同的页面,也会有相同的部分。例如可能会有相同的头部导航。

但是如果每个页面都独自开发,这无疑增加了我们开发的成本。所以我们会把页面的不同部分拆分成独立的组件,然后在不同页面就可以共享这些组件,避免重复开发。

注意:局部组件需要通过components引入

在vue里,所有的vue实例都是组件

代码示例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        button {
            margin: 50px;
            width: 200px;
            height: 30px;
            background-color: burlywood;
            border-width: 0;
        }
    </style>
</head>

<body>

    <div id="app">
        <!-- 不使用组件 -->
        <button @click="count++">我被点击了{{count}}次</button>
        <!-- 使用组件 -->
        <counter></counter>
        <!-- 局部组件 -->
        <button-couner></button-couner>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        // 全局申明组件
        Vue.component("counter", {
            template: `<button @click="count++">我被点击了{{count}}次</button>`,
            data() {
                return {
                    count: 0
                }
            }
        });

        // 局部组件
        const buttonC = {
            template: `<button @click="count++">我被点击了{{count}}次</button>`,
            data() {
                return {
                    count: 0
                }
            }
        };

        new Vue({
            el: "#app",
            data() {
                return {
                    count: 0
                }
            },
            //使用局部组件
            components: {
                'button-couner': buttonC,
            }
        })
    </script>
</body>

</html> 

Last modification:June 24, 2020
如果觉得我的文章对你有用,请随意赞赏