gpt4 book ai didi

javascript - Vue md-input with Vuex 仅在一个方向上更新

转载 作者:行者123 更新时间:2023-12-01 11:12:00 25 4
gpt4 key购买 nike

我有一个 Vue 应用程序,其中输入元素绑定(bind)到这样的:

<template>
<input v-model="this.$store.state.myvalue"/>
</template>

和 VueX store/index.js:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
state: {
myvalue: null
},
mutations: {},
actions: {},
modules: {}
});

当我用 Vue devtools 修改 myvalue 时,输入的值也会改变,但是当我改变输入字段中的值时,状态变量不会改变。我究竟做错了什么?我是 VueX 的新手。

最佳答案

虽然不建议使用 vuex 状态直接绑定(bind) View 层,但 vuex 更适合用于业务逻辑,您可以通过以下方式实现更改用户输入的状态:

[1] two-way data binding: use v-model directive & bind the state in it. On user input, the state will be updated. On changing state programmatically, the element's value will be updated & reflect on dom.

.vue文件

<template>
<input v-model="$store.state.myvalue"/>
</template>

[2] manually create two-way data-binding.

.vue文件

<template>
<input :value="getMyValue" @input="handleInput"/>
</template>

<script>
export default {
methods: {
handleInput (value) {
this.$store.commit('UPDATE_MY_VALUE', { value })
}
},
computed: {
getMyValue () {
return this.$store.state.myvalue
}
}
}
</script>

存储文件

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
state: {
myvalue: null
},
mutations: {
UPDATE_MY_VALUE (state, { value }) {
state.myvalue = value
}
},
actions: {},
modules: {}
});

关于javascript - Vue md-input with Vuex 仅在一个方向上更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com