gpt4 book ai didi

javascript - 如何监听来自vuex的compute数组的变化

转载 作者:行者123 更新时间:2023-12-02 22:50:16 26 4
gpt4 key购买 nike

我有一个计算数组,它是根据商店的状态组装的:

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来创建一组与答案绑定(bind)的输入。它看起来像:

<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

我的问题:如果我更改输入的值,计算的 setter 将不会被触发。我会收到消息

"Error: [vuex] do not mutate vuex store state outside mutation handlers."

我知道我不能直接修改状态,但我不知道如何调度操作,如 official website 的示例。有人可以帮忙吗?非常感谢。

最佳答案

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>

关于javascript - 如何监听来自vuex的compute数组的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58211882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com