如何侦听来自 vuex 的计算数组的变化



我有一个计算数组,它由存储的状态组装而成:

computed: {
...mapGetters([
'$tg',
]),
...mapState({
podcastList: state => state.listening.podcastList,
}),
tabList: {
get() {
const questionTitle = this.$tg('questions');
const list = this.podcastList.map((poadcast, index) => ({
...poadcast,
title: `${questionTitle}${index + 1}`,
answers: [...poadcast.answers],
}));
return list;
},
set(value) {
// I want dispatch action here..
console.log('set', value);
},
},
}

podcastList的构造是一个对象数组:

[ 
{ 
id: 1,  
answers: [ 
{ id: 1, content:'foo'}, { id: 2, content: 'bar'}
]
}, //.....
]

我正在使用v-for来制作一组绑定answersinput。 它看起来像:

<div class="columns is-vcentered" v-for="(answer, index) in tab.answers" :key="index">
<input type="text" v-model="answer.content"/>
</div>
// tab is an element of my tabList

我的问题:如果我更改了输入的值,则不会触发计算的设置器。我会收到消息

"错误:[vuex] 不会在突变处理程序之外更改 vuex 存储状态。">

我知道我不能直接修改状态,但我不知道如何调度动作作为官方网站的例子。有人可以帮忙吗?多谢。

v-model只有在将tabList映射到其中(类似于组件中的v-model="tabList"(时才有效。

您必须直接更改每个答案,方法是使用value@input而不是v-model

<div class="columns is-vcentered" v-for="(answer, index) in tab.answers" :key="index">
<input type="text" :value="answer.content"
@input="$store.commit('updateAnswer', { podcastId: tab.id, answerId: answer.id, newContent: $event.target.value })" />
</div>
// tab is an element of my tabList

updateAnswer突变像:

mutations: {
updateAnswer (state, { podcastId, answerId, newContent }) {
state.listening.podcastList
.find(podcast => podcast.id === podcastId)
.map(podcast => podcast.answers)
.find(answer => answer.id === answerId).content = newContent;
}
}

--

您也许可以通过创建一个方法来减少样板:

methods: {
updateAnswer(tab, answer, event) {
this.$store.commit('updateAnswer', { podcastId: tab.id, answerId: answer.id, newContent: event.target.value });
}
}

并像这样使用它:

<input type="text" :value="answer.content" @input="updateAnswer(tab, answer, $event)" />


或者通过创建一个组件(可以是功能性的(:

Vue.component('answer', {
template: `
<input type="text" :value="answer.content"
@input="$store.commit('updateAnswer', { podcastId: tab.id, answerId: answer.id, newContent: $event.target.value })" />
`
props: ['tab', 'answer']
})

并像这样使用它:

<div class="columns is-vcentered" v-for="(answer, index) in tab.answers" :key="index">
<answer :tab="tab" :answer="answer"/>
</div>

最新更新