组件使用的注意事项

108 阅读1分钟

组件命名 abc-demo 或 demo

   var app=new Vue({
            el:'#demo',
         //局部注册
         components:{
            'demo-tag':{
                 template:'<div>demo中的组件</div>'
                }
            },
            data:{
            }
            
        })

template 必须被一个DOM元素包裹

var app=new Vue({
            el:'#demo',
         //局部注册
         components:{
            'demo-tag':{
                                
                 template:'<div>demo中的组件</div>' //必须被DOM元素包裹
                }
            },
            data:{
            }
            
        })

组件中可以拥有 computed methods data等选项 但是data必须是方法

点击按钮+1 实例 虽然DOM三次调用同一个组件但是每个按钮互不干扰 每个按钮返回的对象是分开的

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="demo">
        <demo-tag></demo-tag> <!-- 局部组件 -->
        <demo-tag></demo-tag> 

        <demo-tag></demo-tag> <!-- 局部组件 -->

    </div>

    <script>
        var app = new Vue({
            el: '#demo',
            //局部注册
            data: {
            },
            components: {
                'demo-tag': {
                    template: '<button @click="count++">{{count}}</button>',
                    data: function () {
                        return {
                            count: 2
                        }
                    }
                }
            }

        })
    </script>
</body>

</html>