使用模板文字的动态 Vue 组件导入路径

Posted

技术标签:

【中文标题】使用模板文字的动态 Vue 组件导入路径【英文标题】:Dynamic Vue component import path using template literals 【发布时间】: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)

这很愚蠢。我可以将后台插入逻辑移到父组件中,并使用&lt;slot /&gt; 将其插入每个child,这样就可以达到我的目的,但这似乎过于声明性了。我的清单目前有 10 项,并且可能会增加,而且几乎肯定会在未来发生变化。

【问题讨论】:

试试 const Background = require(~/path/to/image/background-number-$prop-from-parent.svg) 【参考方案1】:

你可以试试这个技巧..

<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。它可能适用于您的情况。

【讨论】:

谢谢,这绝对是超级有帮助的,并为我指明了正确的方向。 不客气。请确保在此处发布您的问题的最终解决方案,以便其他人可以从中受益:)

以上是关于使用模板文字的动态 Vue 组件导入路径的主要内容,如果未能解决你的问题,请参考以下文章

Vuejs 中的动态导入

Vue.js 动态图像路径未加载

如何将外部 HTML 模板动态导入和解析到 Vue 组件中?

vue中动态加载图片报错

路由器级别的 Vue 3 动态组件

vue中怎么动态添加img的路径