如何在iView的Modal弹窗内嵌套弹出新的Modal?
解决iView Modal回调中
this指向问题,实现嵌套Modal弹出 哈哈,这个问题我之前在项目里踩过一模一样的坑!你遇到的核心问题是点击事件回调里的this没有指向Vue实例,所以才会出现this为null、无法调用this.$Modal的情况。下面给你几个靠谱的解决方案:
方案1:使用箭头函数(最推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this。这里你的render已经用了箭头函数,外层的this就是Vue实例,把点击回调改成箭头函数就能直接拿到正确的this:
this.$Modal.confirm({ render: (h) => { return h('Button', { props: { value: this.value, type: 'primary' }, on: { click: (e) => { // 换成箭头函数 this.$Modal.confirm({ render: (h) => { return h('Input', { }) } }) } } }) } })
方案2:提前保存Vue实例的引用
如果习惯用普通函数,可以在render函数里先把Vue实例的this存到一个变量(比如self)里,之后在回调里用这个变量代替this:
this.$Modal.confirm({ render: (h) => { const self = this; // 保存Vue实例的引用 return h('Button', { props: { value: this.value, type: 'primary' }, on: { click: function (e) { self.$Modal.confirm({ // 用self访问Vue实例 render: (h) => { return h('Input', { }) } }) } } }) } })
方案3:用bind绑定this
可以通过bind方法强制把回调函数的this绑定到Vue实例上,这样在回调里就能正常使用this.$Modal了:
this.$Modal.confirm({ render: (h) => { return h('Button', { props: { value: this.value, type: 'primary' }, on: { click: function (e) { this.$Modal.confirm({ render: (h) => { return h('Input', { }) } }) }.bind(this) // 绑定Vue实例的this } }) } })
为什么会出现这个问题?
你原本用的是普通function作为点击回调,在这种情况下,回调函数的this会指向触发事件的DOM元素(或者在严格模式下是undefined),而不是Vue实例,所以自然没法调用this.$Modal。上面三种方法都是为了让回调里的this(或者替代变量)指向Vue实例,这样就能正常调用Modal方法了。
内容的提问来源于stack exchange,提问作者user7693832
相关产品推荐
相关产品推荐

