如何通过 Vuex 和组合 API 在 Vue 中使用 v-model?

3 vue.js

<template>
    <div>
        <h1>{{ counter }}</h1>
        <input type="text" v-model="counter" />
    </div>
</template>

<script>
    import { computed } from 'vue'
    import { useStore } from 'vuex'
    export default {
        setup() {
            const store = useStore()
            const counter = computed(() => store.state.counter)
            return { counter }
        },
    }
</script>
Run Code Online (Sandbox Code Playgroud)

当输入值改变时如何改变存储中计数器的值

我在控制台中收到此错误:

[操作失败:计算值是只读的]

小智 5

尝试这个:

...
const counter = computed({
  get: () => store.state.counter,
  set: (val) => store.commit('COUNTER_MUTATION', val)
})
...
Run Code Online (Sandbox Code Playgroud)

https://v3.vuejs.org/api/compulated-watch-api.html#compulated