createApp 修改props
来源:8-7 Message 组件改进为函数调用形式
598木马
2020-11-06
import { createApp } from 'vue'
import MessageVue from '@/base/message/message.vue'
import { Message, MessageType } from '@/interface/globalInterface'
import createTeleport from '@/hook/createTeleportHook'
interface MessageCreate {
messageList: Message[];
messageCreate: any;
messageDom: null | HTMLElement;
message: (message: string, type: MessageType, timeout?: number) => void;
success: (message: string, timeout?: number) => void;
warning: (message: string, timeout?: number) => void;
}
export const $message: MessageCreate = {
messageList: [],
messageCreate: null,
messageDom: null,
message (message, type: MessageType, timeout = 2000) {
if (!this.messageCreate) {
if (message) {
this.messageList = [{ id: new Date().getTime(), message, type: type }]
this.messageCreate = createApp(MessageVue, {
message: this.messageList
})
this.messageDom = createTeleport('message')
this.messageCreate.mount(this.messageDom)
}
} else {
if (message) {
this.messageList.push({ id: new Date().getTime(), message, type: type })
this.messageCreate._props = { message: this.messageList }
}
}
setTimeout(() => {
if (this.messageDom) {
this.messageCreate.unmount(this.messageDom)
this.messageDom.remove()
}
this.messageList = []
}, timeout)
},
success (message, timeout = 2000) {
this.message(message, 'success', timeout)
},
warning (message, timeout = 2000) {
this.message(message, 'warning', timeout)
}
}
我想做一个element那种的数组message,但我不知道应该怎么去动态修改createApp()后实例的props值,目前这个代码传递不了值,我在message组建中拿不到props的新值,只有第一次创建时的值,如果我再次调用$message(), this.messageList的值更新了,并且走了对应该逻辑,但在message组件只有第一次实例时的值, 我用watch那些都不能得到更新的值
写回答
1回答
-
同学你好 很专业的问题 instance 上面的 props 的值是不可以更改的,这个值是 readonly 的,你可以在组件内部创建一个响应式对象, const messageCopy = ref(props.message) 然后在实例上改变这个值。
const mountNode = document.createElement('div') document.body.appendChild(mountNode) // vm 返回的是整个组件响应式对象 你可以 console 出来看看 const vm = messageInstance.mount(mountNode) as any setTimeout(() => { vm.messageCopy = 'new message' }, timeout)
012020-11-10
相似问题