看一个小需求:
看一段代码:
// h1组件
Vue.component("H",{
template:`
<h1>{{n}}</h1>
`,
props:["t"],
data:function(){
return {
n:this.t
}
}
})
//加法组件
Vue.component("Add",{
template:`
<button @click="addson">+</button>
`,
methods: {
addson(){
this.$emit("addbind");
}
}
})
//减法组件
Vue.component("Sub",{
template:`
<button @click="subson">-</button>
`,
methods: {
subson(){
this.$emit("subbind");
}
}
})
new Vue({
template:`
<div>
<H v-bind:t="n"/>
<Add v-on:addbind="add"/>
<Sub v-on:subbind="sub"/>
</div>
`,
el:"#app",
data:{
n:0
},
methods: {
add(){
this.n++
},
sub(){
this.n--
}
}
})
当点击加号或者减号时,父组件中的n值会发生变化,但是H组件中的值没有变化,为什么呢?
你的子组件里用了
n
变量去接收与父组件通信的t
,只会在第一次初始化子组件的时候拿到值,如果你直接用t
就可以观察到变化了,想要继续使用n
,你需要动态监听t
的变化并给n
赋值。