使用iview如何双向绑定弹窗?

父组件

<li @click="logClick">登录</li>
<Modal :modalValue="modalValue" @on-close="closeDialog()"></Modal>


// script

data () {
    return {
        modalValue: false,
    }
},
methods: {
    logClick() {
      this.modalValue = true
    },
    closeDialog(attr) {
      this.modalValue = false
    },
}

子组件

<template>
<div>
  <Button type="primary">
    显示对话框
  </Button>
  <Modal v-model="modalValue" @on-ok="ok" @on-cancel="cancel">
    
  </Modal>
  </div>
</template>
<script>
export default {
  props: {
    modalValue: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      
    }
  },
  methods: {
    ok(modalValue) {
      this.$emit('on-close', modalValue);
    },
    cancel(modalValue) {
      this.$emit('on-close', modalValue);
    }
  }
}
</script>

弄了一下午到现在,可以点击打开关闭,但是提示warning双向绑定问题
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "modalValue"

思路: 点击登录 -> 传入modalV=true给子组件 -> 子组件显示 -> 点击关闭 -> 传出关闭事件 -> 父组件通过关闭事件将modalV=false

测试: 如果data里创建MV: this.modalValuev-model绑定上去,那么点击连窗口都不会弹出了。。

阅读 5.6k
3 个回答

改成v-bind:value="modalValue"
不用v-model绑定

# 2个方法

第一个 :

// 父组件
<dialog-apply :visible.sync="dialogApplyVisible" />

// 子组件
<el-dialog
      :visible.sync="visible"
      title="申请"
      :before-close="onClose"
>

onClose() {
  this.$emit('update:visible', false)
}

第二个 :

// 父组件
<dialog-apply :visible.sync="dialogApplyVisible" @close='dialogApplyVisible = false' />

// 子组件
<el-dialog
      :visible.sync="visible"
      title="申请"
      :before-close="onClose"
>

onClose() {
  this.$emit('close')
}

这2个方法 , :before-close 是关键 ;

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题