[英]Vue.js Dynamic Component - Template not showing components data
我正在嘗試使用VueJs構建測驗游戲,直到現在一切都順利進行,但是現在我開始使用動態組件 ,因此在顯示數據時遇到了問題。
我有一個啟動組件(“啟動視圖”),當用戶單擊“啟動”按鈕時,我希望將其替換為實際的“測驗”組件(“進行中”)。 這樣可以順利進行。 但是,在第二個組件模板中,用{{ self.foo }}
引用的數據不再顯示,沒有任何錯誤消息。
我的實現方式如下:
startComponent:
startComponent = {
template: '#start-component',
data: function () {
return {
QuizStore: QuizStore.data
}
},
methods: {
startQuiz: function () {
this.QuizStore.currentComponent = 'quiz-component';
}
}
}
};
和模板:
<script type="x-template" id="start-component">
<div>
<button v-on:click="startQuiz()">
<span>Start Quiz</span>
</button>
</div>
</script>
注意:我使用的是x-templates,因為它在某種程度上使Python / Flask應用程序的其余部分最有意義。 但是,所有內容都包裝在{% raw %}
因此括號不是問題。
測驗部分:
quizComponent = {
template: '#quiz-component',
data: function () {
return {
QuizStore: QuizStore.data,
question: 'foo',
}
};
和模板:
<script type="x-template" id="quiz-component">
<div>
<p>{{ self.question }}</p>
</div>
</script>
如您所見,我正在使用QuizStore存儲所有狀態。
商店:
const QuizStore = {
data: {
currentComponent: 'start-component',
}
};
在主要的.html文件中,我正在實現動態組件,如下所示:
<div id="app">
<component :is="QuizStore.currentComponent"></component>
</div>
那么有效的方法是:
什么不起作用:
{{ self.question }}
數據未顯示。 並且它不會引發錯誤消息。 我不明白的是:
QuizStore.currentComponent = 'startComponent'
渲染quizComponent,那么數據將整齊顯示。 <quiz-component></quiz-component>
(而不是動態組件),它也可以正常工作。 this.
不涉及當前活動的動態組件-所以我想這是錯誤的嗎? 但是話又說回來,我不明白為什么沒有錯誤信息... 我不知道這里是什么問題-有人嗎?
您的父組件可能不知道其子組件會遇到一些問題,並且QuizStore的構造具有一個data
層,您在設置currentComponent
時無需考慮這一data
層。
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>
最終,以下工作:
我只是將<component :is="QuizStore.currentComponent"></component>
包裝在父組件(“ index-component”)中,而不是直接將其放置在主html文件中:
<div id="app">
<index-component></index-component>
</div>
在index-component內:
<script type="x-template" id="index-component">
<div>
<component :is="QuizStore.currentComponent"></component>
</div>
</script>
也許這一直是正確的方法,也許不是,但是現在可以了:)非常感謝Roy的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.