使用一个方法,打开弹窗并接收返回值

示例

  • 父组件
<template>
  <div>
    <el-button @click="open1">打开弹窗1</el-button>
    <el-button @click="open2">打开弹窗2</el-button>
    <module-1 ref="module1" />
    <module-2 ref="module2" />
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import module1 from './components/module-1.vue'
import module2 from './components/module-2.vue'
export default {
  components: { module1, module2 },
  data() {
    return {}
  },
  methods: {
    open1() {
      const func = value => {
        ElMessage(`输入的为:${value}`)
      }
      this.$refs.module1.open(func)
    },
    open2() {
      this.$refs.module2.open().then(value => {
        ElMessage(`输入的为:${value}`)
      })
    }
  }
}
</script>
  • 子组件(通过传递方法使用)
<template>
  <el-dialog title="提示" v-model="visible" width="30%">
    <span>
      <el-input v-model="value" placeholder="请输入内容" />
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      value: '',
      callBack: null
    }
  },
  methods: {
    // 打开弹窗
    open(cb) {
      this.callBack = cb
      this.visible = true
    },
    // 点击确认
    submit() {
      if (this.callBack) {
        this.visible = false
        this.callBack(this.value)
      }
    }
  }
}
</script>
  • 子组件(通过Promise链式调用)
<template>
  <el-dialog title="提示" v-model="visible" width="30%">
    <span>
      <el-input v-model="value" placeholder="请输入内容" />
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      value: '',
      callBack: null
    }
  },
  methods: {
    // 打开弹窗
    open() {
      return new Promise(cb => {
        this.callBack = cb
        this.visible = true
      })
    },
    // 点击确认
    submit() {
      if (this.callBack) {
        this.visible = false
        this.callBack(this.value)
      }
    }
  }
}
</script>
Logo

前往低代码交流专区

更多推荐