一、为什么我们需要.sync这个“神器”?
想象一下这个场景:你正在开发一个电商网站,有个商品卡片组件(子组件),需要让用户能够调整购买数量,同时实时反映到父组件的总价计算中。
按照最基础的Vue组件通信方式,你会这样写:
父组件:
<template>
<div>
<ProductCard
:quantity="productQuantity"
@update:quantity="productQuantity = $event"
/>
总价:{
{ productQuantity * productPrice }}元
</div>
</template>
<script>
export default {
data() {
return {
productQuantity: 1,
productPrice: 99
}
}
}
</script>
子组件:
<template>
<div class="product-card">
<button @click="decrease">-</button>
<span>{
{ quantity }}</span>
<button @click="increase">+</button>
</div>
</template>
<script>
export default {
props: ['quantity'],
methods: {
increase() {
this.$emit('update:quantity', this.quantity + 1)
},
decrease() {
this.$emit('update:quantity', this.quantity - 1)
}
}
}
</script>
看出问题了吗?每次数据更新都要:定义props → 定义自定义事件 → 在父组件监听事件 → 手动更新数据。这就像每次调电视音量都要:拿起遥控器 → 按下按钮 → 等待确认 → 看到变化。太麻烦了!
这就是.sync修饰符要解决的痛点:简化父子组件的双向数据流。
二、.sync修饰符:Vue给你的“数据遥控器”
.sync本质上是一个语法糖,它让上面的代码变得简洁明了:
父组件变身:
<template>
<div>
<ProductCard :quantity.sync="productQuantity" />
总价:{
{ productQuantity * product

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



