Categories
Vue Answers

How to watch store value with Vue 3 composition API?

Spread the love

In Vue 3’s Composition API, you can watch a store value by using the watch function provided by Vue.

To do this we write:

import { ref, watch } from 'vue';
import { useStore } from 'vuex'; // If you're using Vuex

export default {
  setup() {
    const store = useStore(); // Assuming you're using Vuex

    // Define a ref to store the value you want to watch
    const myStoreValue = ref(store.state.someValue);

    // Watch for changes in the store value
    watch(
      () => store.state.someValue, // Getter function
      (newValue, oldValue) => {
        // This callback will be triggered whenever the value changes
        console.log('Store value changed:', newValue);
        // Update the ref with the new value
        myStoreValue.value = newValue;
      }
    );

    // You can also use watchEffect if you don't need access to the old value
    // watchEffect(() => {
    //   myStoreValue.value = store.state.someValue;
    // });

    return {
      myStoreValue
    };
  }
};

In this example, we import ref and watch from Vue.

We import useStore from Vuex to access the store instance.

Inside the setup() function, we define a reactive reference (myStoreValue) to store the value from the store.

We use the watch function to watch for changes to the store’s value.

The first argument to watch is a getter function that returns the value we want to watch (in this case, store.state.someValue).

The second argument is a callback function that will be executed whenever the value changes.

Inside this callback, you can perform any actions you need to with the new value.

Finally, we return myStoreValue from the setup() function so it can be used in the template.

This setup will ensure that myStoreValue always reflects the current value of store.state.someValue, and the callback will be triggered whenever someValue changes in the store.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *