[英]Vue.js - Dynamic component import in data and computed properties
I have component 'Page' that should display a component which is retrieved via its props. 我有组件“页面”,应该显示通过其道具检索的组件。
I managed to get my component loads when I harcode my component path in my component data like this : 当我在组件数据中这样编码组件路径时,我设法获得了组件负载:
<template>
<div>
<div v-if="includeHeader">
<header>
<fv-header/>
</header>
</div>
<component :is="this.componentDisplayed" />
<div v-if="includeFooter">
<footer>
<fv-complete-footer/>
</footer>
</div>
</div>
</template>
<script>
import Header from '@/components/Header/Header';
import CompleteFooter from '@/components/CompleteFooter/CompleteFooter';
export default {
name: 'Page',
props: {
componentPath: String,
includeHeader: Boolean,
includeFooter: Boolean
},
data() {
componentDisplayed: function () {
const path = '@/components/my_component';
return import(path);
},
},
components: {
'fv-header': Header,
'fv-complete-footer': CompleteFooter,
},
}
</script>
But with the data I cannot refer to my props within my function as this is undefined. 但是使用数据我无法在函数中引用我的道具,因为这是未定义的。
I tried to used computed properties instead of data but I have the error "src lazy?0309:5 Uncaught (in promise) Error: Cannot find module '@/components/my_component'. But the module exists! But maybe not at that time ? 我尝试使用计算属性而不是数据,但出现错误“ src lazy?0309:5未捕获(承诺)”错误:找不到模块'@ / components / my_component'。但是该模块存在!但也许当时不存在?
computed: {
componentDisplayed: function () {
const path = `@/components/${this.componentPath}`;
return import(path);
},
},
There must be away to deal with that but I am quite a beginner to vue.js :) 必须解决这个问题,但我是vue.js的初学者:)
Instead of trying to import the component in your child component, instead import it in the parent component and pass the entire component as a prop. 与其尝试在子组件中导入组件,不如将其导入父组件并将整个组件作为道具传递。
<template>
<div :is="component" />
</template>
<script>
export default {
name: "page",
props: {
component: {
required: true
}
}
};
</script>
And in the parent 而在父母
<page :component="component" />
and 和
import Page from './components/Page';
// and further down
data () {
return {
component: HelloWorld
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.