javascript - 使用模板字面量的动态 Vue 组件导入路径

标签 javascript vue.js webpack ecmascript-6 nuxt.js

编辑

因此,以下从技术上回答了这个问题,并且是基于 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/

相关文章:

vue.js - 具有分页无限滚动的 Vuexfire bindFirebaseRef

laravel - 如何在VueJs中访问axios中的 `PromiseValue` `response`

webpack - 如何使用 historyApiFallback 和代理远程 api 请求来设置 webpack 开发服务器?

javascript - ES6 和多次导出的导入问题

javascript - 如何通过vue.js计算SVG viewBox?

javascript - Javascript如何处理函数参数

reactjs - 如何将基础 CSS 与 webpack 和 React 一起使用?

javascript - $在 AngularJs 中注入(inject)

Javascript getTime() 提供令人困惑的结果

javascript - 如何以编程方式在 ember js 中的其他组件/ View 中添加组件或 View