<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>组件与复用</title>
</head>
<body>
<!--自动识别最新稳定版本的Vue.js-->
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="app">
<my-component></my-component>
</div>
<script>
Vue.component('my-component',{
template:'<div>这里是组件的内容</div>'
});
var app = new Vue({
el:'#app'
})
</script>
</body>
</html>

组件与复用.png
template 的 DOM 结构必须被一个元素包含,如果直接写成“这里是组件内容”,不带“<div> </div>” 是无法渲染的。
在Vue 实例中,使用components 选择可以局部注册组件,注册后的组件只有在该实例作用域中有效。组件中也可以使用components 选项来注册组件,使组件可以嵌套。例如:
<div id="app2">
<my-component2></my-component2>
</div>
<script>
var Child = {
template:'<div>局部注册组件的内容</div>'
}
var app = new Vue({
el:'#app2',
components:{
'my-component2':Child
}
})
</script>

局部注册组件的内容.png
Vue 组件的模板在某些情况下会受到HTML的限制,比如<table>内规定只允许是<tr> 、 <td>、<th> 等这些表格元素,所以在<table>内直接使用组件是无效的。这种情况下,可以使用特殊的 is 属性来挂载组件,如下:
<div id="app3">
<table>
<tbody is="my-component3"></tbody>
</table>
</div>
<script>
Vue.component('my-component3',{
template:'<div>这里是组件的内容</div>'
});
var app = new Vue({
el:'#app3'
})
</script>
tbody 在渲染时,会被替换为组件的内容。<ul>、<ol>、<select>。

IS属性.png
除了template选项外,组件中还可以像 Vue 实例那样使用其它的选项比如data、computed、methods 等。但是在使用 data 时,和实例稍有区别,data 必须是函数,然后将数据return 出去,例如:
<div id="app4">
<my-component4></my-component4>
</div>
<script>
Vue.component('my-component4',{
template:'<div>{{ message }}</div>',
data:function(){
return{
message:'组件内容4'
}
}
});
var app = new Vue({
el:'#app4'
})
</script>

组件内容4.png
JavaScript 对象是引用关系,所以如果 return 出的对象引用外部的一个对象,那这个对象就是共享的,任何一个修改都会同步。比如下的示例:
<div id="app5">
<my-component5></my-component5>
<my-component5></my-component5>
<my-component5></my-component5>
</div>
<script>
var data = {
counter:0
};
Vue.component('my-component5',{
template:'<button @click="counter++">{{ counter }}</button>',
data:function(){
return data;
}
});
var app = new Vue({
el:'#app5'
})
</script>

data.png
组件使用了3次,但是点击任意一个<button>,3个的数字都会加1,那是因为组件的data引用的是外部的对象,这肯定不是我们期望的效果,所以给组件返回一个新的data对象来独立,例如:
<script>
Vue.component('my-component5',{
template:'<button @click="counter++">{{ counter }}</button>',
data:function(){
//return data;
return {
counter:0
}
}
});
var app = new Vue({
el:'#app5'
})
</script>

1.png
本文标题:Vue.js 组件与复用
本文链接:https://www.haomeiwen.com/subject/hpfpjctx.html
网友评论