0

我正在使用 Vue3 组合 API。我有一个需要与商店同步的输入字段,以防商店中的数据发生变化,它应该被更新

代码

const store = useStore()
const savedAge = computed(() => store.state.profile.age)
// The saved is async and can be updated at anytime in store 

const age = ref(savedAge.value)

<!-- template -->
<input v-model="age" /> // here the age is null event if savedAge value has updated in store

请注意,我不希望与 store 进行两种方式绑定,如果 store 值已更新,我希望我的响应属性更新

我如何实现这一目标?

4

3 回答 3

1

您可以watchEffect()在本地副本store.state.profile.age更改时使用它来更新它。这将允许您将本地副本的更改与存储区隔离,直到您准备好提交:

<template>
  <input v-model="age">
  <button @click="save">Save</button>
</template>

<script>
import { ref, watchEffect } from 'vue'

export default {
  setup() {
    const age = ref(0)
    const store = useStore()

    watchEffect(() => age.value = store.state.profile.age)

    return {
      age,
      save: () => store.commit('SAVE_AGE', age.value),
    }
  }
}
</script>

演示

于 2021-05-08T07:03:19.970 回答
1

由于您不需要双向绑定,因此请尝试将 value 属性直接绑定到存储:

<input :value="store.state.profile.age" /> 
于 2021-05-07T15:08:53.877 回答
0

您可以这样做:value@change但最好了解您要实现的目标。

const store = useStore();
const ageChange = (e)=>{doSomethingWith(e.target.value)};
return {store, ageChange};
<!-- template -->
<input :value="store.state.profile.age" @change="ageChange"/> 
于 2021-05-07T15:16:35.737 回答