我有一个由存储状态组装的计算数组:
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
来创建一个由input
组成的组,它是answers
的绑定。看上去:
<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存储状态之外的变异处理程序。
我知道我不能直接修改状态,但我不知道如何将该操作作为官方网站的示例进行调度。有人能帮忙吗?非常感谢。
发布于 2019-10-02 19:55:04
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>
https://stackoverflow.com/questions/58211882
复制相似问题