父子组建通信 通过一个很经典的实例演示Vue 2.0 与 3.0 中的区别
Vue3.0 的实现方式
* 原始实现
import testSubVue from './testSub.vue';
components:{
testSubVue
},
const data = reactive({
money:10000
})
return {
...toRefs(data)
}
<span>小明的爸爸现在有{{money}}钱</span>
<testSubVue :money="money" @update:money = "money=$event"></testSubVue>
2. 在子组件中
<button @click="costMoney">花钱</button>
<span>小明的爸爸还剩下{{am}}元</span>
props:["money"],
emits:['update:money'],
setup(props,ctx) {
const am = computed(()=> {
return props.money
})
const costMoney =()=> {
console.log('子组件花钱了..........')
ctx.emit('update:money',props.money - 100)
}
return {
am,
costMoney
}
}
- 原始实现的方式稍微复杂 使用v-model 可以简写成这样
<testSubVue v-model:money="money"></testSubVue>
下面记录下在 Vue 2.0 时候父子组建数据同步的实现过程
import testSubVue from './testSub.vue';
components:{
testSubVue
},
data() {
return {
money:10000
}
},
<span>小明的爸爸有{{money}}元</span>
<testView :money = "money" @update:money="money=$event"></testView>
2. 子组件中的实现
props:["money"],
methods: {
costAction() {
console.log('点击花钱的事件........')
this.$emit("update:money",this.money - 100)
}
}
<span>小明每次花100元</span>
<button @click="costAction">花钱</button>
<br>
<span>爸爸还剩下{{money}}元</span>
<testView :money.sync="money"></testView>
- 前端新手如果笔记中存在任何问题或者还有更好的实现方式还望过路大神不吝赐教!