vue 注册组件的使用详解(2)
由于my-component组件是注册在#app元素对应的Vue实例下的,所以它不能在其它Vue实例下使用。
<div id="app2">
<!-- 不能使用my-component组件,因为my-component是一个局部组件,它属于#app-->
<my-component></my-component>
</div>
<script>
new Vue({
el: '#app2'
});
</script>
二、组件注册语法糖
以上组件注册的方式有些繁琐,Vue.js为了简化这个过程,提供了注册语法糖
// 全局注册,my-component1是标签名称
Vue.component('my-component1',{
template: '<div>This is the first component!</div>'
})
var vm1 = new Vue({
el: '#app1'
})
Vue.component()的第1个参数是标签名称,第2个参数是一个选项对象,使用选项对象的template属性定义组件模板。
使用这种方式,Vue在背后会自动地调用Vue.extend()。
components实现局部注册
var vm2 = new Vue({
el: '#app2',
components: {
// 局部注册,my-component2是标签名称
'my-component2': {
template: '<div>This is the second component!</div>'
},
// 局部注册,my-component3是标签名称
'my-component3': {
template: '<div>This is the third component!</div>'
}
}
}
三、父组件和子组件
我们可以在组件中定义并使用其他组件,这就构成了父子组件的关系。
<!DOCTYPE html>
<html>
<body>
<div id="app">
<parent-component>
</parent-component>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var Child = Vue.extend({
template: '<p>This is a child component!</p>'
})
var Parent = Vue.extend({
// 在Parent组件内使用<child-component>标签
template :'<p>This is a Parent component</p><child-component></child-component>',
components: {
// 局部注册Child组件,该组件只能在Parent组件内使用
'child-component': Child
}
})
// 全局注册Parent组件
Vue.component('parent-component', Parent)
new Vue({
el: '#app'
})
</script>
</html>
这段代码的运行结果如下

四、使用script或template标签
尽管语法糖简化了组件注册,但在template选项中拼接HTML元素比较麻烦,这也导致了HTML和JavaScript的高耦合性。
