VUE-组件基础
1.基本示例
<div id="app8">
<button-counter></button-counter>
</div>
<script>
Vue.component('button-counter',{
data:function(){
return{
count:0
}
},
template:'<button v-on:click="count++">你点击我{{count}} 次</button>'
});
new Vue({el:"#app8"})
</script>
2.组件可复用
<div id="app8">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
<script>
Vue.component('button-counter',{
data:function(){
return{
count:0
}
},
template:'<button v-on:click="count++">你点击我{{count}} 次</button>'
})
new Vue({el:"#app8"})
</script>
注意当点击按钮时,每个组件都会各自独立维护它的 count。因为你每用一次组件,就会有一个它的新实例被创建。
3.data必须是一个函数
当我们定义这个 <button-counter> 组件时,你可能会发现它的 data 并不是像这样直接提供一个对象:
data: {
count: 0
}
取而代之的是,一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝:
data: function () {
return {
count: 0
}
}
如果 Vue 没有这条规则,点击一个按钮就可能会像如下代码一样影响到其它所有实例
4.通过Prop向子组件传递参数
<div id="app8">
<blog-post title="My journey with Vue" name="1"></blog-post>
<blog-post title="Blogging with Vue" name="2"></blog-post>
<blog-post title="Why Vue is so fun" name="3"></blog-post>
</div>
<script>
Vue.component('blog-post',{
props:['title','name'],
template:'<h3>{{title}}<b>{{name}}</b></h3>'
})
new Vue({el:"#app8"})
</script>
输出:
My journey with Vue1
Blogging with Vue2
Why Vue is so fun3

浙公网安备 33010602011771号