[英]Dynamic Vue component import path using template literals
編輯
因此,以下從技術上回答了這個問題,並且基於 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
(文檔)。
有問題的組件 ( 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,
}
}
( 來源)
這很愚蠢。 我可以將背景插入邏輯移動到父組件並使用<slot />
將其插入每個child
組件中,這將達到我的目的,但這似乎過於聲明性了。 我的清單目前有 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>
如此處所見。 它可能適用於您的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.