Search code examples
vue.jsvuexvuejs3vue-composition-apivuex4

Vue ref/reactive with default value


I am using Vue3 composition API. I have an input field which needs to be in sync with store, incase the data changes in store it should be updated

Code

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

Please note I don't want two way binding with store, I want my reactive property to update if store value has been updated

How do I achieve this?


Solution

  • You could use watchEffect() to update your local copy with store.state.profile.age whenever it changes. This would allow you to isolate the local copy's changes from the store until you're ready to commit:

    <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