Back-end front-end notes: Two-way data binding problem between vue parent and child components

Recently, when using element-ui's Dialog component to be encapsulated into a separate component for use, the child component needs to return the closed dialog state to the parent component, that is, to achieve the two-way data binding problem between the parent and child components. The example code is as follows:

Parent component :

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

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

Subcomponent :

<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>

Reference: https://segmentfault.com/a/1190000011783590

Guess you like

Origin blog.csdn.net/qq_40378034/article/details/112257227