后端的前端笔记:vue父子组件之间双向数据绑定问题

最近在使用element-ui的Dialog组件二次封装成独立组件使用时,子组件需要将关闭dialog状态返回给父组件,也就是实现父子组件之间双向数据绑定问题,实例代码如下:

父组件

<template>
  <div>
    <el-button type="primary" @click="openDialog">点击打开Dialog</el-button>
    <childComponent title="Dialog对话框" :openStatus="openStatus" @dialog="closeDialog"></childComponent>
  </div>
</template>

<script>
import childComponent from './ChildComponent'
export default {
  data () {
    return {
      openStatus: false
    }
  },
  components: {
    childComponent
  },
  methods: {
    openDialog () {
      this.openStatus = true
    },
    closeDialog (data) {
      // 子组件触发父组件事件,修改openStatus的值
      this.openStatus = data
    }
  }
}
</script>

子组件

<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
    <span>Dialog对话框</span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleClose">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: {
    title: String,
    openStatus: Boolean
  },
  data () {
    return {
      // dialogVisible变量缓存openStatus数据
      dialogVisible: this.openStatus
    }
  },
  // 监听父组件对props属性openStatus的修改,并同步导组件内的dialogVisible属性
  watch: {
    openStatus (val) {
      this.dialogVisible = val
    }
  },
  methods: {
    handleClose () {
      // 关闭对话框时向父组件发送事件通知
      this.$emit('dialog', false)
    }
  }
}
</script>

参考:https://segmentfault.com/a/1190000011783590

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邋遢的流浪剑客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值