【问题标题】:vue.js import a component dynamicallyvue.js 动态导入组件
【发布时间】:2018-11-21 22:01:52
【问题描述】:

我正在尝试动态导入组件,但我的所有组件和 vuex 变量似乎都未定义。

function loadChart(chartName){
    let chart = chartName + '.vue'
    return System.import('@/components/charts/' + chart)
  }

  export default {
    name: "SingleChart",
    data() {
      return {
        chartTitle: this.$store.getters.getSingleChartTitle,
        chartName: this.$store.getters.getSingleChartName
      }
    },
    methods: {},
    computed: {},
    watch: {},
    props: [],
    components: {
        Chart: () => loadChart(this.chartName)
    }
  }

我得到了错误

Reason: Error: Cannot find module './undefined.vue'.

【问题讨论】:

  • 尝试不使用Chart的箭头函数。
  • @Thomas 谢谢,你能举个例子说明一下吗?
  • 为了确定问题出在this.chartName,您是否尝试通过将 ITS 名称硬编码为loadChart 的参数来加载模块?
  • 是的,对模块名称进行硬编码可以正常工作。我开始认为在评估组件属性的 vue.js 生命周期中,商店不可用。我也尝试过通过路由器传递一个道具,但这也不可用。一定有办法做到这一点,我确定我不是第一个需要这个的人。
  • 可能是因为箭头函数使用了this父上下文,所以this不是Vue实例。请参阅本节上方的警告消息:vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

标签: javascript dynamic import vuejs2 vue-component


【解决方案1】:

基于the Vuex state page,您可能没有像您引用的那样注入存储来使用它(this.$store...)

Vuex 提供了一种机制,可以使用 store 选项(由 Vue.use(Vuex) 启用)将 store 从根组件“注入”到所有子组件中:

const app = new Vue({
    el: '#app',
    // provide the store using the "store" option.
    // this will inject the store instance to all child components.
    store,
    components: { Counter },
    template: `
      <div class="app">
        <counter></counter>
      </div>
})

【讨论】:

  • @'Miles Grimes' 谢谢,但我已经注入了商店。我开始认为,在评估组件属性的 vue.js 生命周期中,商店不可用。所以我需要一个替代方案。
  • 这似乎是相关的,虽然没有使用 Vuex:medium.com/@codetheorist/…
猜你喜欢
  • 2020-12-09
  • 2021-01-05
  • 2017-06-14
  • 2017-09-28
  • 2021-05-16
  • 1970-01-01
  • 2019-09-15
  • 2019-08-03
  • 1970-01-01
相关资源
最近更新 更多