使用vuex状态管理后,在 input 中使用 v-model 来进行双向数据绑定,在修改 input 中值的时候会抛出一个错误
1.可以不使用 v-model 来进行双向数据绑定,使用 :value=' ' 来,然后设置一个 监听器来推动 state 的更新( @input=' ' )
vue 模板
<template>
<div class="hello">
<input type="text" :value="text" @input='update'>
<span>{{ddd}}</span>
<p ref="ppp">啦啦啦</p>
<input type="text" v-focus>
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
name: 'HelloWorld',
data () {
return {
ddd: ''
}
},
computed: {
...mapState(['text'])
},
methods: {
update (e) {
// 在这里来 更新 state 里的某一个值
this.$store.dispatch('updataText', e.target.value)// 触发 actions 来 推动 mutations
this.$refs.ppp.innerText = '465'
}
},
watch: {
text: function () {
this.ddd = this.$store.state.text
}
},
directives: {
focus: {
// 自定义指令
inserted: function (el) {
el.focus()
}
}
}
}
</script>
actions.js 里内容
const actions = {
updataText (context, val) {
context.commit('modify', val)
}
}
export default actions
mutations.js 里内容
const mutations = {
modify (state, newVal) {
state.text = newVal
console.log(state.text)
}
}
export default mutations
state.js 里内容
export default {
text: '46546'
}
// 具体参考 官方文档:https://vuex.vuejs.org/zh-cn/forms.html
浙公网安备 33010602011771号