Vuex 的 2 路数据绑定 [英] 2 way data binding with Vuex
问题描述
在下面的代码中,我以两种方式将 textarea 的输出绑定到 p 元素中,一次来自组件的内部状态,一次来自 Vuex.Vuex 状态确实显示了初始值,但是当我添加或删除文本时该值不会更新(因为它正确地将第一个 textarea 绑定到内部数据).导致此问题的区别是什么?
组件代码:
<div><div><textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="internal_state"></textarea><p>{{ internal_state }}</p><小时><textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="this.$store.state.vuex_state"></textarea><p>{{ this.$store.state.vuex_state }}</p><小时>
</模板><脚本>导出默认{name: '写入区域',数据 () {返回 {内部状态:''}},方法: {}}
Vuex 代码:
从'vue'导入Vue从 'vuex' 导入 VuexVue.use(Vuex)export const store = new Vuex.Store({严格:真实,状态: {计数器:0,vuex_state: '起始字符串'},吸气剂:{vuex_getter1:(状态)=>{返回 state.vuex_string}}})
Vuex 状态应通过突变更新.请参阅有关此确切问题的文档.解决方案不是使用 v-model,而是绑定到 textarea
的 :value
,然后使用自定义事件来改变输入时的 Vuex 状态:https://vuex.vuejs.org/en/forms.html
//...计算:{...地图状态({消息:状态 =>状态.obj.message})},方法: {更新消息 (e) {this.$store.commit('updateMessage', e.target.value)}}
另一个选项是在同一个计算属性中创建一个 setter 和 getter:
//...计算:{信息: {得到 () {返回 this.$store.state.obj.message},设定值) {this.$store.commit('updateMessage', value)}}}
In the code below I'm 2 way binding the output of a textarea into a p element, once from the component's internal state and once from Vuex. The Vuex state does show the initial value, but the value doesn't update as I add or delete text (as it does correctly with the 1st textarea bound to the internal data). What is the difference that is causing this issue?
Component code:
<template>
<div>
<div>
<textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="internal_state"></textarea>
<p> {{ internal_state }}</p>
<hr>
<textarea name="textarea1" id="txtid" cols="40" rows="30" v-model="this.$store.state.vuex_state"></textarea>
<p> {{ this.$store.state.vuex_state }}</p>
<hr>
</div>
</div>
</template>
<script>
export default {
name: 'WriteArea',
data () {
return {
internal_state: ''
}
},
methods: {
}
}
</script>
Vuex code:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
strict: true,
state: {
counter: 0,
vuex_state: 'starting string'
},
getters: {
vuex_getter1: (state) => {
return state.vuex_string
}
}
})
Vuex state should be updated via a mutation. See the documentation for this exact problem. Solution is not to use v-model, but instead to bind to the :value
of the textarea
and then have a custom event to mutate the Vuex state on input:
https://vuex.vuejs.org/en/forms.html
<input :value="message" @input="updateMessage">
// ...
computed: {
...mapState({
message: state => state.obj.message
})
},
methods: {
updateMessage (e) {
this.$store.commit('updateMessage', e.target.value)
}
}
The other option is to create a setter and getter in the same computed property:
<input v-model="message">
// ...
computed: {
message: {
get () {
return this.$store.state.obj.message
},
set (value) {
this.$store.commit('updateMessage', value)
}
}
}
这篇关于Vuex 的 2 路数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!