美文网首页
Vue的.sync修饰符与this.$emit('update:

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

作者: 刘其瑞 | 来源:发表于2022-02-11 18:03 被阅读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)
 }

相关文章

网友评论

      本文标题:Vue的.sync修饰符与this.$emit('update:

      本文链接:https://www.haomeiwen.com/subject/fqczkrtx.html