根据nuxt中的url参数动态加载组件
我在 nuxt 中有一个页面,分为两部分.第一部分是基于 url 参数填充动态内容的普通模板结构.第二部分是应根据此数据加载的组件.我正在尝试像这样完成它:
<模板><h1>{{myData.header}}</h1><p>{{myData.text}}</p><我的组件></我的组件></div></模板><脚本>导出默认{组件: {'我的组件': () =>导入('@/components' + this.myData.component)},异步异步数据(上下文){返回 {我的数据:context.params.myData}}}</脚本>
但这不起作用.有没有办法做到这一点?
我熟悉使用 <my-component :is="myData.component"></my-component>
的可能性.但是,这需要我明确导入每个组件,我想避免这种情况.
我昨天找到了解决方案.它需要这样做.
<模板><h1>{{myData.header}}</h1><p>{{myData.text}}</p><component :is="componentInstance"></component></div></模板><脚本>导出默认{计算:{组件实例(){常量名称 = this.myData.component返回()=>导入(`./components/${name}`)}},异步异步数据(上下文){返回 {我的数据:context.params.myData}}}</脚本>
本文中的更多信息:https://itnext.io/vue-a-pattern-for-idiomatic-performant-component-registration-you-might-not-know-about-9f3c091846f5.
I have a page in nuxt that is divided in two parts. The first part is a normal template structure filled with dynamic content based on the url param. The second part is a component that should be loaded based on this data. I am trying to accomplish it like this:
<template>
<div>
<h1>{{myData.header}}</h1>
<p>{{myData.text}}</p>
<my-component></my-component>
</div>
</template>
<script>
export default {
components: {
'my-component': () => import('@/components' + this.myData.component)
},
async asyncData(context) {
return {
myData: context.params.myData
}
}
}
</script>
But this is not working. Is there a way to accomplish this?
I am familiar with the possibility to use <my-component :is="myData.component"></my-component>
. However, this requires me to import every component explicitly and I would like to avoid this.
I found a solution to this yesterday. It needs to be done like this.
<template>
<div>
<h1>{{myData.header}}</h1>
<p>{{myData.text}}</p>
<component :is="componentInstance"></component>
</div>
</template>
<script>
export default {
computed: {
componentInstance () {
const name = this.myData.component
return () => import(`./components/${name}`)
}
},
async asyncData(context) {
return {
myData: context.params.myData
}
}
}
</script>
More info in this article: https://itnext.io/vue-a-pattern-for-idiomatic-performant-component-registration-you-might-not-know-about-9f3c091846f5.
相关文章