谷粒商城34 - 前端基础 VUE-组件化基础

组件化介绍


使用组件的注意事项

全局声明组件

全局声明注册一个组件的demo代码如下.
使用Vue.component("counter",
注意组件中的data,不能用对象, 而是方法的声明.
声明了组件后, 可以复用多次 , 直接写组件的名称即可, 如下的<counter></counter>

<body>

    <div id="app">
        <button v-on:click="count++">我被点击了 {{count}} 次</button>

        <counter></counter>
        <counter></counter>
        <counter></counter>
        <counter></counter>
        <counter></counter>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>


    <script>
        //1、全局声明注册一个组件
        Vue.component("counter", {
            template: `<button v-on:click="count++">我被点击了 {{count}} 次</button>`,
            data() {
                return {
                    count: 1
                }
            }
        });

        new Vue({
            el: "#app",
            data: {
                count: 1
            }
        })
    </script>
</body>

如下 所示, 每一个按钮, 都可以多次点击 .

局部声明组件

使用const 声明局部组件.
对局部组件的引用

components: {
                'button-counter': buttonCounter
            }

页面上的使用方法

   <button-counter></button-counter> <br>
<body>

    <div id="app">
        <button-counter></button-counter> <br>
        <button-counter></button-counter> <br>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>


    <script>
        //2、局部声明一个组件
        const buttonCounter = {
            template: `<button v-on:click="count++">我被点击了 {{count}} 次~~~</button>`,
            data() {
                return {
                    count: 1
                }
            }
        };

        new Vue({
            el: "#app",
            data: {
                count: 1
            }
            ,
            components: {
                'button-counter': buttonCounter
            }
        })
    </script>
</body>

页面效果如下

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/107744425