[Vuejs]-How to store selected value in Vuex store

0👍

In action

https://codesandbox.io/s/vuex-store-forked-vls9w

App.vue

<template>
  <div>
    <h2>{{ getLang }}</h2>
    <select v-model="langSelect">
      <option value="en">en</option>
      <option value="tr">tr</option>
    </select>
  </div>
</template>

<script>
export default {
  name: "LangChange",
  data() {
    return {
      langSelect: "",
    };
  },
  computed: {
    getLang () {
      return this.$store.getters.getLanguage;
    },
  },
  watch: {
    langSelect: function (val, oldVal) {
      this.$store.dispatch("setLanguage", val);
    },
  },
};
</script>

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const state = {
  lang: ""
};

const mutations = {
  STORE_LANGUAGE(state, payload) {
    state.lang = payload;
  }
};

const actions = {
  setLanguage(context, number) {
    context.commit("STORE_LANGUAGE", number);
  }
};

const getters = {
  getLanguage(state) {
    return state.lang;
  }
};

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
});

Leave a comment