组件,也就是一个标签,只不过这个标签是自定义的而已,它的注册方式分为全局和局部两种
组件注册方式
全局组件注册方式
这种方式利用的Vue.component
<h3>全局组件:</h3>
<div id="app">
<panda></panda>
</div>
<script type="text/javascript">
Vue.component('panda', {
template:'<p>全局 panda</p>'
});
new Vue({
el : "#app"
});
</script>
在上面的代码后面加上这么一些附加代码:
<!--附加代码-->
<div id="test">
<panda></panda>
</div>
<script type="text/javascript">
new Vue({
el: "#test"
})
</script>
结果如下:
局部注册方式
利用的是构造器里面的components
<h3>局部组件:</h3>
<div id="app1">
<div-panda></div-panda>
</div>
<script type="text/javascript">
new Vue({
el : "#app1",
components: {
'div-panda' : {
template: "<p>局部 panda</p>"
}
}
})
</script>
在上面的结果“全局注册”的附加代码,结果如下
所以说呢,全局注册和局部注册的作用域是不同的,根据需要灵活选择
组件中的props
如下面的代码:
<h3>props的用法</h3>
<div id="app3">
<atree here="Beijing"></atree>
</div>
<script type="text/javascript">
new Vue({
el: "#app3",
data : {
message: "xi'an"
},
components: {
"atree" : {
template: '<div>there is {{here}}</div>',
props: ['here']
}
}
})
</script>
分析上面的代码:在上面的组件的模板中,含有一个here
这个变量,props中也包含着here
,在html
中也包含here
并且给它赋了值,当你运行这段代码的时候,确实显示的值就是html
中的here的值,也就说明了这似乎就是一种可以传递信息的方式,组件的props属性说明,我需要怎样的值,然后在html中,给组件所需要的值,其实这不就是“通信”吗?
props
对应的数组中的字符串是不能包含“-”连接符号的,而是应该写成驼峰的样子
组件使用data值
同样先看这样一段代码:
<h3>props与data的搭配使用</h3>
<div id="app4">
<btree v-bind:location="message" here="Beijing"></btree>
</div>
<script type="text/javascript">
new Vue({
el : "#app4",
data : {
message: "xi'an"
},
components: {
'btree': {
template: "<div>there is {{location}}</div>",
props: ['location']
}
}
});
</script>
重点就在这里v-bind:location="message"
,在这里使用了Vue的v-bind
指令,绑定了location
这个属性,并且它的值来源于data
里面的message
,也就是实现了 动态地绑定父组件的数据到子模板的props
使用Component动态绑定组件
这里要用到的就是is
,如下面的代码所示:
<h3>component动态绑定组件</h3>
<div id="app6">
<comment v-bind:is="who">
</comment>
<button v-on:click="change">change component</button>
</div>
<script type="text/javascript">
var componentA = {
template : "<p>this is component A</p>"
};
var componentB = {
template : "<p>this is component B</p>"
};
var componentC = {
template : "<p>this is component C</p>"
};
new Vue({
el : "#app6",
data : {
who: 'componentA'
},
components: {
"componentA" : componentA,
"componentB" : componentB,
"componentC" : componentC
},
methods : {
change: function() {
if(this.who == 'componentA') {
this.who = 'componentB';
}else if(this.who == 'componentB') {
this.who = 'componentC';
}else {
this.who = 'componentA';
}
}
}
})
上面的代码实现的就是,初始的时候绑定的是组件A,通过的是is,让它等于data中的who
,当点击按钮之后,会执行相应的方法,也就是动态改变who
的值,从而切换不同的组件
组件间的通讯
这部分请参考,组件之间的通信