Vue/Nuxt: How to make a component be truly dynamic? Vue/Nuxt: How to make a component be truly dynamic? vue.js vue.js

Vue/Nuxt: How to make a component be truly dynamic?


From the documentation: Emphasis mine

<!-- Component changes when currentTabComponent changes --><component v-bind:is="currentTabComponent"></component> 

In the example above, currentTabComponent can contain either:

  • the name of a registered component,
  • or a component’s options object

If currentTabComponent is a data property of your component you can simply import the component definition and directly pass it to the component tag without having to define it on the current template.

Here is an example where the component content will change if you click on the Vue logo.

Like this:

<component :is="dynamic" />

...

setComponentName() {    this.dynamic = () => import(`@/components/${this.componentName}.vue`);},


Solution for Nuxt only

As of now its possible to auto-import components in Nuxt (nuxt/components). If you do so, you have a bunch of components ready to be registered whenever you use them in your vue template e.g.:

<MyComponent some-property="some-value" />

If you want to have truly dynamic components combined with nuxt/components you can make use of the way Nuxt prepares the components automagically. I created a package which enables dynamic components for auto-imported components (you can check it out here: @blokwise/dynamic).

Long story short: with the package you are able to dynamically import your components like this:

<NuxtDynamic :name="componentName" some-property="some-value" />

Where componentName might be 'MyComponent'. The name can either be statically stored in a variable or even be dynamically created through some API call to your backend / CMS.

If you are interested in how the underlying magic works you can checkout this article: Crank up auto import for dynamic Nuxt.js components


you are talking about async components. You simply need to use the following syntax to return the component definition with a promise.

Vue.component('componentName', function (resolve, reject) {  requestTemplate().then(function (response) {    // Pass the component definition to the resolve callback    resolve({      template: response    })  });})