问题描述
道具被初始化,但是在.mount
之后它们消失了。我应该如何使用动态加载的组件正确设置props
?
import {createApp} from 'vue'
blockView = createApp(Block);
blockView.props = {
type: json['type'],title: json['title'],subtitle: json['subtitle']
}
blockView.mount(this.$refs.container)
解决方法
道具对应用程序不可用,仅对组件不可用,但是我发现它们可以将值传递给应用程序。
1。使用注入/提供
const app = Vue.createApp({
inject: ['name'],// ...etc
})
app.provide("name","Ludwig")
app.mount('#app2')
这不完全是一个道具(需要在挂载之前通过),但是可以为您工作。
更多信息:https://v3.vuejs.org/api/application-api.html#provide
2。嵌套为渲染函数并包装
通过包装渲染功能,可以传递道具。如果您再次将其包装在自定义安装函数中,则可以自定义以允许传递道具。
// the app as a component
const appComponent = Vue.defineComponent({
name: "appComponent",props: {
name: {}
},// ...etc
})
// wrap mount function
const mountApp = (selector,props) => {
// the actual app is just a simple render function
const app = Vue.createApp({
components: { appComponent },render() {
return Vue.h(appComponent,props)
}
})
// mount to the passed selector
app.mount(selector);
}
// call function with props
mountApp('#app1',{
name: "Darla"
});
示例fiddle