.sync 修饰符

195 阅读1分钟

sync修饰符是在写子组件改变父组件里面数据的代码时,可以用到的语法糖.

这行代码

<comp :foo.sync="bar"></comp>

等价于下面这行代码

<comp :foo="bar" @update:foo=" bar = val"></comp>

当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:

this.$emit('update:foo', newValue)

当需要同时监听多个prop值时

<comp v-bind.sync="bar"></comp>
其中bar为一个对象假设bar为{value1:1,value2:2}

html中的写法

<comp v-bind.sync="bar"></comp>

子组件props写法

props:["value1",value2]

子组件触发更新写法

this.$emit("update:value1", newValue)
this.$emit("update:value2", newValue)