Vue- Import vue components dynamically

2019-06-27 04:10发布

I have many components, i want to import then on demand. i have a drop down which actually contains components list, that what to load. I tried this example

<component :is="componentLoader"></component>

in script

componentLoader () {
  return () => import('@/components/testDynamic') 
}

testDynamic is a component name(For now i am trying with static component).

Getting this error

GET http://localhost:8080/0.js net::ERR_ABORTED 404
[Vue warn]: Failed to resolve async component: function () {
    return __webpack_require__.e/* import() */(0).then(__webpack_require__.bind(null, "./src/components/testDynamic.vue"));
  }
  Reason: Error: Loading chunk 0 failed.

How to fix this? am i doing any thing wrong? or is there any other way to import components dynamically?

1条回答
forever°为你锁心
2楼-- · 2019-06-27 04:53

You can register async dynamic components locally in a single file component like this:

export default {
  components: {
    'test-dynamic': () => import('@/components/testDynamic'),
    'other-dynamic': () => import('@/components/otherDynamic')
  },
  data () {
    return {
      current: 'test-dynamic'
    }
  }
}

And in your template:

<component :is="current"></component>

If you register multiple components then you would just change the value of current to the desired component.

In the case of many components, you can import an object mapping the component names to their respective file paths, then register them like:

import myComponents from '@/components'

export default {
  components: Object.keys(myComponents).reduce((obj, name) => {
    return Object.assign(obj, { [name]: () => import(myComponents[name]) })
  }, {})
  ...
}

Where myComponents is exported as:

// components/index.js
export default {
  foo: '@/path/to/Foo',
  bar: '@/path/to/Bar',
  ...
}
查看更多
登录 后发表回答