Vue的.sync修饰符与this.$emit('update:

2022-02-11  本文已影响0人  刘其瑞
.sync修饰符的作用

Vue中的数据是单向数据流:父级 prop 的更新会向下流动到子组件中,但是反过来则不行,即子组件无法直接修改父组件中的数据。
但我们常常会遇到需要在子组件中修改父组件数据的场景。.sync修饰符就可以帮助我们实现这种功能。

不使用.sync修饰符时的写法

父组件代码

<template>
  <div>
    <comp :num="num" @update:num="func"></comp>
  </div>
</template>

<script>
export default {
  methods: {
    func (val) {
        this.num = val
    }
  }
}
</script>

子组件代码

handleBtn () {
     this.$emit('update:num', 5)
 }

使用.sync修饰符的写法

父组件代码

<template>
  <div>
    <comp :num.sync="num"></comp>
  </div>
</template>

子组件代码

handleBtn () {
     this.$emit('update:num', 5)
 }
上一篇 下一篇

猜你喜欢

热点阅读