Vue 的 .sync 修饰符

79 阅读1分钟

使用场景

当父组件给子组件传递了一个外部属性,当子组件需要更新这个外部属性时,需要触发一个更新事件通知父组件修改这个属性的值。

  • 子组件 Child.vue
<template>
  <div>
    {{ num }}
    <button @click="$emit('update:amount', num + 1)">
      +1
    </button>
  </div>
</template>

<script>
export default {
  props: ['num']
}
</script>

<style lang="scss" scoped></style>

子组件收到父组件传递的外部属性num,使用$emit订阅一个事件update:amount,当点击 button 时触发,同时传递新的值num+1

常规做法

  • 父组件 Parent.vue
<template>
  <div>
    {{ amount }}
    <Child :num="amount" v-on:update:amount="amount = $event" />
  </div>
</template>

<script>
import Child from './Child.vue'

export default {
  data() {
    return {
      amount: 100
    }
  },
  components: { Child }
}
</script>

<style lang="scss" scoped></style>

在父组件中,使用子组件时可以监听事件update:amount,当事件触发时可以获取到子组件传递的最新值$event,并执行某个操作。

.sync 修饰符

.sync就是一个语法糖,例如常规做法中父组件的:

<Child :num="amount" v-on:update:amount="amount = $event" />

就可以简化为:

<Child :num.sync="amount" />