问题描述
为什么会出现此错误:
错误 [vuex] 不要在变异处理程序之外改变 vuex 存储状态.
什么意思?
当我尝试输入编辑输入文件时会发生这种情况.
It happens when I try to type in the edit input file.
pages/todos/index.vue
pages/todos/index.vue
<template>
<ul>
<li v-for="todo in todos">
<input type="checkbox" :checked="todo.done" v-on:change="toggle(todo)">
<span :class="{ done: todo.done }">{{ todo.text }}</span>
<button class="destroy" v-on:click="remove(todo)">delete</button>
<input class="edit" type="text" v-model="todo.text" v-todo-focus="todo == editedTodo" @blur="doneEdit(todo)" @keyup.enter="doneEdit(todo)" @keyup.esc="cancelEdit(todo)">
</li>
<li><input placeholder="What needs to be done?" autofocus v-model="todo" v-on:keyup.enter="add"></li>
</ul>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
data () {
return {
todo: '',
editedTodo: null
}
},
head () {
return {
title: this.$route.params.slug || 'all',
titleTemplate: 'Nuxt TodoMVC : %s todos'
}
},
fetch ({ store }) {
store.commit('todos/add', 'Hello World')
},
computed: {
todos () {
// console.log(this)
return this.$store.state.todos.list
}
},
methods: {
add (e) {
var value = this.todo && this.todo.trim()
if (value) {
this.$store.commit('todos/add', value)
this.todo = ''
}
},
toggle (todo) {
this.$store.commit('todos/toggle', todo)
},
remove (todo) {
this.$store.commit('todos/remove', todo)
},
doneEdit (todo) {
this.editedTodo = null
todo.text = todo.text.trim()
if (!todo.text) {
this.$store.commit('todos/remove', todo)
}
},
cancelEdit (todo) {
this.editedTodo = null
todo.text = this.beforeEditCache
},
},
directives: {
'todo-focus' (el, binding) {
if (binding.value) {
el.focus()
}
}
},
}
</script>
<style>
.done {
text-decoration: line-through;
}
</style>
stores/todos.js
stores/todos.js
export const state = () => ({
list: []
})
export const mutations = {
add (state, text) {
state.list.push({
text: text,
done: false
})
},
remove (state, todo) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle (state, todo) {
todo.done = !todo.done
}
}
有什么想法可以解决这个问题吗?
Any ideas how I can fix this?
推荐答案
在属于 Vuex 的状态片段上使用 v-model 可能有点棘手.
It could be a bit tricky to use v-model on a piece of state that belongs to Vuex.
并且您在 todo.text
上使用了 v-model
此处:
and you have used v-model
on todo.text
here:
<input class="edit" type="text" v-model="todo.text" v-todo-focus="todo == editedTodo" @blur="doneEdit(todo)" @keyup.enter="doneEdit(todo)" @keyup.esc="cancelEdit(todo)">
使用 :value
读取值并使用 v-on:input
或 v-on:change
执行执行突变的方法在显式 Vuex 突变处理程序中
use :value
to read value and v-on:input
or v-on:change
to execute a method that perform the mutation inside an explicit Vuex mutation handler
此问题在此处处理:https://vuex.vuejs.org/en/forms.html
这篇关于Vuex - 不要在变异处理程序之外改变 vuex 存储状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!