《如何理解 Vue 的 .sync 修饰符》

372 阅读1分钟

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

案例

父组件:

// App.vue
<template>
  <div class="app">
    App.vue 我现在有 {{ total }}
    <hr />
    <Child :num.sync="total" />
    <hr />
    <Child :num="total" @update:num="total = $event" />
  </div>
</template>

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

<style>
.app {
  border: 3px solid red;
  padding: 10px;
}
</style>

上面代码中,<Child :num.sync="total" /> 可以扩展为
<Child :num="total" @update:num="total = $event" />
这就是一个语法糖。

子组件:

// Child.vue
<template>
  <div class="child">
    {{ num }}
    <button @click="$emit('update:num', num + 1)">
      <span> +1 </span>
    </button>
  </div>
</template>

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

<style>
.child {
  border: 3px solid green;
}
</style>

效果如下:

未命名.gif