【问题标题】:Vue ref/reactive with default valueVue ref/reactive 与默认值
【发布时间】:2021-07-29 21:42:49
【问题描述】:

我正在使用 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 值已更新,我希望我的响应属性更新

我如何做到这一点?

【问题讨论】:

    标签: vue.js vuex vuejs3 vue-composition-api vuex4


    【解决方案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>
    

    demo

    【讨论】:

    • 这正是我所缺少的! watchEffect 成功了。谢谢
    【解决方案2】:

    您可以:value@change,但最好了解您想要实现的目标。

    const store = useStore();
    const ageChange = (e)=>{doSomethingWith(e.target.value)};
    return {store, ageChange};
    
    <!-- template -->
    <input :value="store.state.profile.age" @change="ageChange"/> 
    

    【讨论】:

      【解决方案3】:

      由于不需要双向绑定,尝试直接绑定value属性到store:

      <input :value="store.state.profile.age" /> 
      

      【讨论】:

      • 谢谢,但是这样我就不会跟踪用户是否更改了值,如果输入值发生更改,我需要运行更多逻辑。我只想将值存储为默认值,以后可以在用户编辑输入时更改。
      • @sandiprb 使用本地分配的data 来存储价值,然后通过v-model 进行更新如何?还是在用户更改值时运行您的逻辑的 @input: 回调?
      猜你喜欢
      • 1970-01-01
      • 2018-07-21
      • 2017-06-20
      • 2020-12-13
      • 2018-12-03
      • 2019-07-19
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多