可复用性的组件

252 阅读1分钟
使用组件的原因

作用: 提高代码的复用性

组件的使用方法

全局注册

Vue.component('my-component',{
    template:'<div></div>'
})

页面渲染  

<my-component></my-component>

优点: 所有vue实例都可以使用

缺点:权限太大,容错率降低

局部注册

const vue = new Vue({
    el:'#app',
    components:{
        my-component:{
            template:'<div></div>'
        }
    }
})
页面渲染
<my-component></my-component>

注意: vue组件的模板放在某些情况下会受到html标签的限制,比如

中 只能
这些元素,所以直接在 中使用组件是无效的,要想在
中使用组件,用 is 属性挂载组件

<table>
    <tbody is="组件名"></tbody>
</table>

组件使用的奇淫技巧

1.名字: 推荐使用小写字母加 - 进行命名。 如 my-component 命名组件

2.template中的内容必须被一个DOM元素包裹,也可以嵌套 如 template:'<div><span></span></div>'

3.在组件中定义,除了template,还可以定义data,computed,methods

4.data必须是一个函数

new Vue({
    el:'#app',
    components:{
        my-component:{
            template:`<button></button>`,
            data(){
                return {
                    count: 0
                }
            }
        }
    }
})