编辑
因此,以下从技术上回答了这个问题,并且是基于 Husam 的回答。
beforeCreate: function () {
this.$options.components.Background = () =>
import(`~/assets/img/marketing/user-group-backgrounds/user-group-bg-${this.bg}.svg`)
}
将按要求工作,根据 bg
获取背景支柱。唯一的问题是,它是一个 SVG,而不是一个 .vue 文件,并且没有通过 vue-svg-loader
传递,所以我得到错误 Invalid Component definition
.
原始问题
我有一个 vue/Nuxt.js 应用程序,我们在其中使用 vue-svg-loader
(documentation)。
有问题的组件 ( child
) 从其父 ( parent
) 组件中定义的对象中检索几位数据作为 props。
parent
使用 v-for
遍历对象中的顶部条目, 生成 child
对于每个。
每个child
需要不同的背景图像,其路径可以使用以下方法确定:
`~/path/to/image/background-number-${prop-from-parent}`
自 vue-svg-loader
将 SVG 图像视为组件,它提供了我想利用的几个好处,我正在尝试设计一个解决方案,使我能够按照这些思路做一些事情:
<template>
<div class="child">
<Background class="background-image" />
<p>
...
</p>
</div>
</template>
<script>
const Background = import(`~/path/to/image/background-number-${prop-from-parent}`)
export default {
components: {
Background
},
props: {
prop-from-parent: { type: String, required: true }
}
}
</script>
这样做会返回:
NuxtServerError
render function or template not defined in component: Background
我做了研究,发现唯一的解决方案似乎是这样的:
import BackgroundOne from 'path/to/background-one.svg'
import BackgroundTwo from 'path/to/background-two.svg'
import BackgroundThree from 'path/to/background-three.svg'
export default{
components: {
BackgroundOne,
BackgroundTwo,
BackgroundThree,
}
}
( source )
这很愚蠢。我可以将后台插入逻辑移动到父组件并将其插入到每个 child
中使用 <slot />
,它会达到我的目的,但这似乎过于声明。我的列表目前有 10 个项目,并且可能会增加,并且几乎肯定会在未来发生变化。
最佳答案
你可以试试这个技巧..
<script>
export default {
props: {
prop-from-parent: { type: String, required: true }
},
beforeCreate: function () {
const filePath = `~/path/to/image/background-number-${this.prop-from-parent}`
this.$options.components.Background = require(filePath).default
}
}
</script>
As seen here .它可能适用于您的情况。
关于javascript - 使用模板字面量的动态 Vue 组件导入路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52596743/