Vue从零开始总结21
组件分为全局组件和局部组件,所谓全局组件就是你创建的这个组件可以在多个实例当中使用,也就是多个new Vue这样子。而局部组件呢,是在单个实例里面。
管你听没懂,看就完了。
带颜色的代表推荐写法
首先是全局组件,如下:
const my=Vue.extend({
template:`
<div>
<p>我是个组件</p>
</div>`
})
Vue.component('cpn-x',my)
也可以这样写
如下:
Vue.component('cpn-x',{template:`标签内容`})
最后是局部组件,如下:
const my=Vue.extend({
template:`
<div>
<p>我是个组件</p>
</div>`
})
components:{
'cpn-x': my
}
或者直接在components中直接建立
如下:
components:{
'cpn-x':{
template:`标签内容`
}
}
组件也分父子,父当中包含子,例如,在父组件里面写components,里面写子组件。
有的时候,看写在template里面内容很乱,而且胡乱加背景色,所以我们这时候就需要采用组件和模板分离的方法。
普通写法:
<script type="text/x-template" id="one">
<div>
<ul>
<li>我是一个独立的模板</li>
</ul>
</div>
</script>
Vue.component('cpn',{
template:'#one'
})
适用写法:
<template id="one">
<div>
<ul>
<li>我是一个独立的模板</li>
</ul>
</div>
</template>
Vue.component('cpn',{
template:'#one'
})