Load component dynamically based on url parameters in nuxt(根据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.
这篇关于根据nuxt中的url参数动态加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据nuxt中的url参数动态加载组件


- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01