Vue 中的 .sync 修饰符有什么用

101 阅读1分钟

在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以变更父组件,且在父组件和子组件两侧都没有明显的变更来源。

我们通过一个场景来辅助理解一下。

  • 场景描述
    爸爸给儿子打钱,儿子要花钱怎么办?
    答 : 儿子打电话(触发事件)向爸爸要钱
    示例 :
    Father.vue
<template>
 <div class="app">
   App.vue 我现在有 {{total}}
   <hr>
   <Child :money.sync="total"/>
 </div>
</template>

<script>
import Child from "./Child.vue";
export default {
 data() {
   return { total: 10000 };
 },
 components: { Child: Child }
};
</script>

Child.vue

<template>
  <div class="child">
    {{money}}
    <button @click="$emit('update:money', money-100)">
      <span>花钱</span>
    </button>
  </div>
</template>

<script>
export default {
  props: ["money"]
};
</script>

效果:

image.png

由于这样的场景很常见,所以尤雨溪发明了.sync修饰符。

:money.sync="total" === :money="total" v-on:update:money="total=$event"

总结:Vue 中的.sync 修饰符的功能是 : 当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。