Vue2 .sync修饰符的应用


前言

Vue2 .sync修饰符的使用.


一、场景

经常遇到需要关闭各种弹窗的情况, 基于Element的话, 基本就是大量监听close事件, 常用的做法是用一个visible属性来使父子组件建立联系, 控制作为子组件的弹窗的显示隐藏, 那么必然要面临父子组件内visible的同步问题.

你不能让父组件内的visible受到事件影响变为true的情况下, 子组件弹窗里直接控制el-dialog显隐的visible属性依旧是false吧?
同理弹窗关闭后子组件也需要向父组件同步visiblefalse, 两边始终保持一致才好.

我刚开始给出的思路比较简单, 在我不知道这个修饰符的情况下.
就是用props$emit, 对, 就这样互相传, 子组件有关闭事件就向父组件$emit传值来同步.

原始基本是这样, 可以跑一下:

<!-- 子组件son -->
<template>
  <div class="son" v-show="nowVisible">
    <p>{
  { nowVisible }}</p>
    <button @click="closeSon">click to close son</button>
  </div>
</template>
<script>
export default {
     
  name: 'son',
  props: {
     
    visible: {
     
      type: Boolean,
      default: () => false
    }
  },
  data() {
     
	dialogVisible: this.visible
  },
  watch: {
     
    visible: {
     
      handler(newVal) {
     
        this.nowVisible = newVal;
      },
    },
  },
  methods: {
     
	closeSon() {
     
	  this.$emit('closeSon', false);
	}
  }
}
</script>
<!-- 父组件fa -->
<template>
  <div class="fa">
    <button</
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中,.sync 是一个语法糖,它能够简化父子组件之间的数据传递。.sync 修饰符实际上是一个双向绑定的简写形式,它会自动创建一个名为 update:propName 的自定义事件,并且在父组件中监听这个事件,然后更新子组件的数据。 例如,在父组件中使用子组件时,可以通过 v-bind.sync 修饰符将父组件的数据与子组件的数据绑定在一起: ``` <template> <ChildComponent :message.sync="messageFromParent"></ChildComponent> </template> ``` 这里的 .sync 修饰符会自动将子组件的 message 属性与父组件的 messageFromParent 属性进行双向绑定,并且在父组件中监听名为 update:message 的自定义事件,以更新父组件的数据。 ``` <template> <ChildComponent :message.sync="messageFromParent"></ChildComponent> <button @click="updateMessage">Update Message</button> </template> <script> export default { data() { return { messageFromParent: 'Hello World' } }, methods: { updateMessage() { this.messageFromParent = 'Hello Vue' } } } </script> ``` 在子组件中,可以通过 $emit() 方法触发 update:message 事件,以更新父组件的数据。 ``` <template> <div> <input type="text" v-model="message"> <button @click="$emit('update:message', message)">Update Message</button> </div> </template> <script> export default { props: { message: { type: String } } } </script> ``` 这样,父组件和子组件之间就可以通过 .sync 修饰符实现双向数据绑定了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值