Vue : sync修饰符

912 阅读1分钟

.sync修饰符

在某些情况下,我们可能需要对一个 prop 进行“双向绑定”。

简单的方法是 子组件向父组件发送一个事件,父组件监听该事件,然后更新prop

简单的栗子:父子组件通信

父组件:

<template>
  <div id="FatherCom">
    <h4>我是父组件</h4>
    <div v-show="show">能看得见我吗?</div>
    <hr>
    <ChildCom :show="show" @update:show="update_show"/>
  </div>
</template>

<script>
  import ChildCom from './ChildCom'

  export default {
    name: 'FatherCom',
    components: {
      ChildCom
    },
    data() {
      return {
        show: true
      }
    },
    methods: {
      update_show(val) {
        this.show = val
      }
    }
  }
</script>

<style scoped>

</style>

子组件:

<template>
  <div id="ChildCom">
    <h4>我是子组件</h4>
    <button @click="handle" >显示/隐藏</button>
  </div>
</template>

<script>
  export default {
    name: 'ChildCom',
    props:['show'],
    methods:{
      handle(){
        this.$emit('update:show',!this.show)
      }
    }
  }
</script>

<style scoped>

</style>

但是以上父组件定义 自定义事件的步骤过于繁琐了。

可以通过 .sync修饰符简化父组件的代码:

  • 在子组件内触发的事件名要以 update:myPropName 方式命名(尤雨溪要求的),
  • 父组件 :show:show 加上.sync修饰符, 即 :show.sync:show

这样设置父组件就不再需要单独再去绑定@update:show事件了 。

修改代码:

<template>
  <div id="FatherCom">
    <h4>我是父组件</h4>
    <div v-show="show">能看得见我吗?</div>
    <hr>
    <!--<ChildCom :show="show" @update:show="update_show"/>-->
     <ChildCom :show.sync="show" />
  </div>
</template>
 handle(){
       	// 这里要求用 `update:myPropName` 方式命名
        this.$emit('update:show',!this.show)
      }