【发布时间】:2019-03-06 21:29:57
【问题描述】:
编辑
因此,以下从技术上回答了这个问题,并且基于 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) 组件中定义的对象中检索几位数据作为道具。
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)
这很愚蠢。我可以将后台插入逻辑移到父组件中,并使用<slot /> 将其插入每个child,这样就可以达到我的目的,但这似乎过于声明性了。我的清单目前有 10 项,并且可能会增加,而且几乎肯定会在未来发生变化。
【问题讨论】:
-
试试 const Background = require(
~/path/to/image/background-number-${prop-from-parent}.svg)
标签: javascript vue.js webpack ecmascript-6 nuxt.js