vue .sync 修饰符与$emit(update:xxx)

vue .sync 修饰符与$emit(update:xxx)

.sync 修饰符的作用

在对一个 prop 进行“双向绑定,单向修改”的场景下,因为子组件不能直接修改父组件,sync 在 2.3 版本引入,作为一个事件绑定语法糖,利用 EventBus,当子组件触发事件时,父组件会响应事件并实现数据更新,避免了子组件直接修改父组件传过来的内容。

.sync 修饰符之前的写法

父组件需要传一个绑定值同时需要设置一个更新触发函数

1
2
3
<template>
<child :title="title" @update:title="(val) => (title = val)" />
</template>

子组件触发事件

1
this.$emit("update:title", val);

使用.sync 修饰符的写法

父组件

1
2
3
<template>
<child :title.sync="title" />
</template>

子组件

1
this.$emit("update:title", val);

绑定多个值

1
2
3
<template>
<child v-bind.sync="obj" />
</template>
  • 这样会把 obj 对象中的每一个 property (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。
  • 将 v-bind.sync 用在一个字面量的对象上,例如 v-bind.sync=”{ title: obj.title }”,是无法正常工作的。