Blog>
Snippets

Template Refs with Vuex

Show how to use template refs in conjunction with Vuex for managing state, such as setting focus on an input element based on state changes.
// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    shouldFocusInput: false
  },
  mutations: {
    SET_FOCUS(state, value) {
      state.shouldFocusInput = value;
    }
  },
  actions: {
    setFocus(context, value) {
      context.commit('SET_FOCUS', value);
    }
  }
});
This is the Vuex store definition file. It initializes the Vuex store with a state property 'shouldFocusInput' that controls whether an input should be focused, and corresponding mutations and actions to modify this state.
// main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store';

new Vue({
  store,
  render: h => h(App)
}).$mount('#app');
This is the main entry file where Vue instance is created and linked with the Vuex store.
<template>
  <input ref="myInput" v-model="inputValue">
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    };
  },
  computed: {
    shouldFocusInput() {
      return this.$store.state.shouldFocusInput;
    }
  },
  watch: {
    // Watch for changes in the shouldFocusInput computed property
    shouldFocusInput(newValue) {
      if (newValue) {
        this.$nextTick(() => {
          this.$refs.myInput.focus();
        });
      }
    }
  }
};
</script>
This is the Vue component that includes an input element with a template ref 'myInput'. It watches for changes on 'shouldFocusInput' from the Vuex store, and if focus is requested, it sets the focus on the input element using the $nextTick method to ensure the DOM has updated.