vue 中的 .sync 修饰符 与 this.$emit('update:key', value)

vue 中 .sync 修饰符,是 2.3.0+ 版本新增的功能

在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以变更父组件,且在父组件和子组件两侧都没有明显的变更来源。

这也是为什么我们推荐以 update:myPropName 的模式触发事件取而代之。举个例子,在一个包含 title prop 的假设的组件中,我们可以用以下方法表达对其赋新值的意图:

在子组件中,props 中 使用 title,然后修改 title 为新的值,并通知父组件:

this.$emit('update:title', newTitle)

然后父组件可以监听那个事件并根据需要更新一个本地的数据 property。例如:

<text-document
  v-bind:title="doc.title"
  v-on:update:title="doc.title = $event"
></text-document>

为了方便起见,我们为这种模式提供一个缩写,即 .sync 修饰符:

<text-document v-bind:title.sync="doc.title"></text-document>

 

当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:

<text-document v-bind.sync="doc"></text-document>

这样会把 doc 对象中的每一个 property (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。

 

实际应用场景:

vue dialog 弹窗中使用

父组件引入一个子组件,子组件是一个弹窗,父组件控制弹窗打开,子组件关闭弹窗时通知父组件,父组件不用再监听更新事件

父组件:

<template>
  <div>
      <el-button @click="open">打开弹窗</el-button>
      <my-dialog :sync.visible="dialogVisible" />
  </div>
<template>
<script>
export default {
  data() {
  
return {
    dialogVisible:
false
   }
  },
  methods: {
    open() {
      
this.dialogVisible = true
    }
  }
}
</script>
 

 

子组件中:

需要使用 :before-close 来处理关闭后的操作,不要使用@close 方法,因为传给父组件visible为false后,子组件会监听到visible的变化,会再执行@close方法

<template>
  <el-dialog
    title="新建"
width="70%"
  :visible="visible"
:before-close="close"

@close="close"
>
    <div>子组件</div>
 </el-dialog>
</template>

props: {
    visible: {
      type: Boolean,
      require: true,
      default: false
    }
  },

methods: {
   close() {
      this.$emit('update:visible', false)
   }
}

 

原文地址:https://www.cnblogs.com/aimee2004/p/15776454.html