ElementUI:关闭对话框,使用消息框来实现 - vue2 的写作风格
最编程
2024-03-05 13:12:38
...
那么我就按照官网的写法来做:
<template>
<el-button @click="open">打开弹窗</el-button>
</template>
<script>
export default {
methods: {
async open() {
let sex = '未知'
const h = this.$createElement
await this.$msgbox({
title: '提示',
message: h('p', [
'选择性别',
h('el-select', {
props: {
value: sex
},
on: {
change: val => (sex = val)
},
style: {
marginLeft: '1em'
}
}, ['男', '女', '未知'].map(sex => {
return h('el-option', {
key: sex,
props: {
label: sex,
value: sex
}
})
}))
])
})
alert(sex)
}
}
}
</script>
效果图:
可是问题出现了,改变不了select的值???
百思不得其姐,那只好去看看element源码呗,发现原来是将message赋值给$slots.default
了
那么我立刻就想到message是vnode
的话,何不去用VueComponent
去试试呢?那么就可以改造成:
<template>
<el-button @click="open">打开弹窗</el-button>
</template>
<script>
import Vue from 'vue'
const MessageboxSelect = Vue.component('messagebox-select', {
data() {
return {
value: '未知'
}
},
render() {
const h = this.$createElement
return h('p', [
'选择性别',
h('el-select', {
props: {
value: this.value
},
on: {
change: val => (this.value = val)
},
style: {
marginLeft: '1em'
}
}, ['男', '女', '未知'].map(sex => {
return h('el-option', {
key: sex,
props: {
label: sex,
value: sex
}
})
}))
])
}
})
export default {
methods: {
async open() {
const h = this.$createElement
await this.$msgbox({
title: '提示',
message: h(MessageboxSelect)
})
}
}
}
</script>
但是这样会引发一个问题,弹窗消失后再打开会出现之前保留的状态,而不是重新生成初始状态
那么就好办了,只要把Vue.component()
这一步放到open
里面就可以了
<template>
<el-button @click="open">打开弹窗</el-button>
</template>
<script>
import Vue from 'vue'
export default {
methods: {
async open() {
let sex = '未知'
const h = this.$createElement
await this.$msgbox({
title: '提示',
message: h(Vue.component('messagebox-select', {
data() {
return {
value: sex
}
},
render() {
const h = this.$createElement
return h('p', [
'选择性别',
h('el-select', {
props: {
value: this.value
},
on: {
change: val => (sex = this.value = val)
},
style: {
marginLeft: '1em'
}
}, ['男', '女', '未知'].map(sex => {
return h('el-option', {
key: sex,
props: {
label: sex,
value: sex
}
})
}))
])
}
}))
})
alert(sex)
}
}
}
</script>
搞掂!!