[Vuejs]-Vue.js Dynamic Component – Template not showing components data

0👍

You may have some issues with your parent component not knowing about its child components, and your construct for QuizStore has a data layer that you don’t account for when you set currentComponent.

const startComponent = {
  template: '#start-component',
  data: function() {
    return {
      QuizStore: QuizStore.data
    }
  },
  methods: {
    startQuiz: function() {
      this.QuizStore.currentComponent = 'quiz-component';
    }
  }
};

const QuizStore = {
    data: {
        currentComponent: 'start-component',
    }
};

new Vue({
  el: '#app',
  data: {
    QuizStore
  },
  components: {
    quizComponent: {
      template: '#quiz-component',
      data: function() {
        return {
          QuizStore: QuizStore.data,
          question: 'foo'
        }
      }
    },
    startComponent
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<script type="x-template" id="start-component">
  <div>
    <button v-on:click="startQuiz()">
            <span>Start Quiz</span>
        </button>
  </div>
</script>

<script type="x-template" id="quiz-component">
  <div>
    <p>{{ question }}</p>
  </div>
</script>

<div id="app">
  <component :is="QuizStore.data.currentComponent"></component>
</div>

0👍

The following worked in the end:

I just wrapped <component :is="QuizStore.currentComponent"></component> in a parent component (“index-component”) instead of putting it directly in the main html file:

<div id="app">
    <index-component></index-component>
</div>

And within the index-component:

<script type="x-template" id="index-component">
    <div>
        <component :is="QuizStore.currentComponent"></component>
    </div>
</script>

Maybe this would have been the right way all along, or maybe not, but it works now 🙂 Thanks a lot Roy for your help!

Leave a comment