1

Is possible in Vue.js call component by variable name?

Components are registred:

import Component1 from 'component1'
import Component2 from 'component2'
import Component3 from 'component3'

...

components: {
    Component1, Component2, Component3
},

And i am searching for something like this:

created() {
    var componentName = 'Component1';
    this.components[componentName]
}

2 Answers 2

1

You can access the components property like this:

this.$options.components[componentName]
Sign up to request clarification or add additional context in comments.

Comments

0

Just a basic example on how you can use dynamic component:

link to jsFiddle to play around: link here

<div id="app">
   <component v-bind:is="currentPage">
       <!-- component changes when currentPage changes! -->
       <!-- output: Updated About -->
   </component>
</div>

new Vue({
  el: '#app',
  data: {
    currentPage: 'home'
  },
  components: {
    home: {
      template: "<p>Home</p>"
    },
    about: {
      template: "<p>About</p>"
    },
    contact: {
      template: "<p>Contact</p>"
    }
  },
  mounted(){
   this.$options.components['about'].template = "<p>Updated About</p>"
    this.currentPage = 'about'
  }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.