我有一个 Vue 单页应用程序,需要使用不同的组件进行更新。用户应该能够随时更改所使用的组件。
为了实现这一目标,我创建了一个对象,对于每个键,它返回一个与所需类型相对应的 Vue 组件。这样,如果我有所需组件的名称(及其一些数据),我可以通过调用 myComponents[name](data)
来获取该组件。
myComponents = {
heading: ( data ) => Vue.component( 'heading', {
... // use data
render: function() {
...
}
} ),
content: ( data ) => Vue.component( 'content', {
...
} )
// and more of the same
}
在我的主应用程序中,我使用了一个包含所需组件键的数据对象,以及一个将这些键映射到对象的渲染函数,以接收必要的组件。更新数据对象应该更新映射到页面的组件。
var page = new Vue( {
el: '#page',
data: function() {
return {
page_content: [ { type: 'heading', data: 'lorem ipsum' },
{ type: 'content', data: 'more lorem ipsum' } ]
}
},
render: function( h ) {
return h( 'div',
{ attrs: { id: 'page' } },
this.page_content.map( p => myComponents[ p.type ]( p.data ) )
)
}
} )
问题是主渲染函数没有添加组件。该元素留空。为什么会这样?
这是一个相当简单的应用程序,因此我想继续使用渲染函数而不是模板。
最佳答案
答案简单得令人尴尬。
我忘记从返回的组件创建一个元素,只是将原始 Vue 组件直接放入内容数组中。
我的主要渲染函数应该是:
render: function( h ) {
return h( 'div',
{ attrs: { id: 'page' } },
this.page_content.map( p => h( myComponents[ p.type ]( p.data ) ) )
)
}
关于javascript - 在渲染函数中使用动态 Vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56452235/