对于vuex,使用getter获取state数据,并绑定到组件上,是很常规的操作
但是在严格模式下,在属于vuex的state上使用v-model这种需要双向绑定的数据类型,单单使用getter就会报错:
Computed property “searchWebName” was assigned to but it has no setter.
错误代码如下:
<!--vue-->
<template>
<el-form class="searchDiv">
<el-form-item label="网站名称:">
<input class="inputC" v-model="searchWebName" placeholder="网站名称" />
</el-form-item>
</el-form>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
computed: {
...mapGetters(["searchWebName"]),
}
}
</script>
<!--vuex-->
export default new Vuex.Store({
state: {
searchWebName:"",
}
getters: {
searchWebName: state => {
return state.searchWebName;
},
}
})
原因如下:在用户输入是,v-model会视图直接修改vuex中的state中的searchWebName,在严格模式下,由于这个修改不是在mutation函数中执行的,所以这里就会抛出一个错误.
1.使用监听事件提交更改的方式解决这个问题
用vuex的思维解决这个问题,监听input的输入事件,在事件回调中调用action修改state数据
<template>
<input :value="message" @input="updateMessage">
</template>
<script>
import{mapGetters} from "vuex";
export default{
computed: {
...mapState({
message: state => state.obj.message
})
},
methods: {
updateMessage (e) {
this.$store.commit('updateMessage', e.target.value)
}
}
}
</script>
// ...
mutations: {
updateMessage (state, message) {
state.obj.message = message
}
}
2.双向绑定的计算属性:使用带有Setter的双向绑定计算属性:
<!--vue-->
<template>
<el-form class="searchDiv">
<el-form-item label="网站名称:">
<input class="inputC" v-model="searchWebName" placeholder="网站名称" />
</el-form-item>
</el-form>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
computed: {
...mapGetters(["listProject"]),
searchWebName: {
get() {
return this.$store.state.searchWebName;
},
set(value) {
this.$store.commit("SET_WENNAME", value);
}
},
}
}
</script>
<!--vuex-->
export default new Vuex.Store({
state: {
listProject:[],
searchWebName: '',
},
mutations: {
SET_PROJECT_LIST: (state, {
projectlist
}) => {
state.listProject= projectlist
},
SET_WENNAME(state, val) {
state.searchWebName = val
},
},
getters: {
listProject: state => {
return state.listProject;
},
}
})