问题描述
<template>
<component :is="myComponent" />
</template>
<script>
export default {
props: {
component: String,},data() {
return {
myComponent: '',};
},computed: {
loader() {
return () => import(`../components/${this.component}`);
},created() {
this.loader().then(res => {
// components can be defined as a function that returns a promise;
this.myComponent = () => this.loader();
},}
</script>
参考:
https://medium.com/scrumpy/dynamic-component-templates-with-vue-js-d9236ab183bb
Vue js import components dynamically
控制台抛出错误“this.loader() is not a function”或“this.loader().then” is not a function。
解决方法
不确定您为什么会看到该错误,因为 loader
被明确定义为返回函数的计算道具。
然而,created
钩子似乎调用了 loader()
两次(第二次调用是不必要的)。这可以简化:
export default {
created() {
// Option 1
this.loader().then(res => this.myComponent = res)
// Option 2
this.myComponent = () => this.loader()
}
}
更简单的方法是将 loader
重命名为 myComponent
,去掉 myComponent
数据属性:
export default {
//data() {
// return {
// myComponent: '',// };
//},computed: {
//loader() {
myComponent() {
return () => import(`../components/${this.component}`);
},},}