[英]Vue Component not showing store data
我正在建立一個瑣事制造商。 我目前正在編輯頁面上處理一個問題。 名為 EditQAForm 的編輯組件獲取該特定問題的問題和答案,並填充每個相應的 VueX 商店的表單。
我目前在此頁面的答案部分遇到問題。 安裝 EditQAForm 后,它會調用 fetchQuestionAnswers,它會檢索該特定問題的所有答案。 它正確地做到了這一點,但是當我嘗試在頁面上顯示任何答案時,它說表單是空的,盡管我在 Vue DevTools 中看到它不是空的。
(請注意我刪除了與此無關的內容。因此假設您看到的所有方法都存在)
這是為 EditQAForm 安裝的:
mounted() {
//gets the params from the url
this.routeParams = this.$route.params;
//gets the answers that belong to this question
this.fetchQuestionAnswers(this.routeParams.question_id);
//not important for this problem
//get the question that needs to be edited
this.fetchQuestion(this.routeParams.question_id);
},
我如何在 EditQAForm 的計算屬性中調用它:
computed: {
...mapGetters('question', ['formQuestionRoundID', 'questions', 'questionFields']),
...mapGetters('answer', ['answerFields', 'answers']),
//Questions
questionForm: {
get() {
return this.questionFields;
},
},
//Answers
answerForm: {
get() {
return this.answerFields;
},
},
}
這是答案的商店
function initialState() {
return {
answers: [],
answer: null,
form: [
{
id: '',
title: '',
question_id: '',
round_id: '',
correct: false,
},
{
id: '',
title: '',
question_id: '',
round_id: '',
correct: false,
},
{
id: '',
title: '',
question_id: '',
round_id: '',
correct: false,
},
]
}
}
const getters = {
answers(state){
return state.answers;
},
answerFields(state){
return state.form;
},
loading(state){
return state.loading;
},
};
const actions = {
fetchQuestionAnswers({ commit, state }, question_id) {
console.log("Form outside axios:");
console.log(state.form);
commit('setLoading', true);
axios.get('/api/question/' + question_id + '/answers')
.then(response => {
commit('SET_ANSWERS_FORM', response.data);
commit('setLoading', false);
}).catch( error => {
console.log(error.response);
});
},
const mutations = {
SET_ANSWERS_FORM(state, answers){
for(let $i = 0; $i < answers.length; $i++)
{
state.form[$i] = {
id: answers[$i].id,
title: answers[$i].title,
question_id: answers[$i].question_id,
round_id: answers[$i].round_id,
correct: answers[$i].correct,
}
}
// state.answers = answers;
},
UPDATE_TITLE(state, payload){
state.form[payload.order].title = payload.title;
},
UPDATE_QUESTION_ID(state,payload){
state.form[payload.order].question_id = payload.questionID;
},
};
我嘗試輸出的內容:
<div>
<h3 class="pb-3">Is first answer's title not empty?: {{!(answerForm[1].title === '')}}</h3>
<h3 class="pb-3">{{answerForm[0].title }}</h3>
<h3>{{answerForm}}</h3>
</div>
我的屏幕上顯示的內容以及 devtools 告訴我的內容位於 answerForm 數組中:
我以非常相似的方式實現了問題部分。 唯一的區別是表單不是問題存儲中的數組,但除此之外它工作正常。 我究竟做錯了什么?
我認為問題出在這里:
state.form[$i] = {
如果你使用索引來更新數組,它不會觸發反應系統,你會得到一個陳舊版本的渲染組件。 見https://v2.vuejs.org/v2/guide/list.html#Caveats
有多種方法可以解決此問題。 你可以使用Vue.set
或者創建一個全新的數組。
我並不完全清楚為什么您首先要進行所有復制,而不僅僅是使用state.form = answers
,這也可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.