0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

vuex-persistがVue3で動くか試してみた

Posted at

結論

vuex-persistはVue3で動く

環境

vue 3.1.1
vuex 4.0.1
vuex-persist 3.1.3

my-appvue\src\App.vue

<template>
  <div id="app">
    <CountValue />
  </div>
</template>

<script>
import CountValue from './components/CountValue.vue';

export default {
  name: 'app',
  components: {
    CountValue,
  },
};
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

my-appvue\src\main.js

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

const app = createApp(App).use(store);
app.mount('#app');

my-appvue\src\store.js

import { createStore } from 'vuex';
import VuexPersist from 'vuex-persist';
import counter from './store/modules/counter';

const vuexLocalStorage = new VuexPersist({
  key: 'sano-vuex', // The key to store the state on in the storage provider.
  storage: window.localStorage, // or window.sessionStorage or localForage
  // Function that passes the state and returns the state with only the objects you want to store.
  // reducer: state => state,
  // Function that passes a mutation and lets you decide if it should update the state in localStorage.
  //
});

const vueStore = createStore({
  strict: process.env.NODE_ENV !== 'production',
  modules: {
    counter,
  },
  state: {},
  mutations: {},
  actions: {},
  plugins: [vuexLocalStorage.plugin],
});
export default vueStore;

my-appvue\src\store\modules\counter.js

const state = {
  step: 1,
  count: 0,
};

const getters = {
  step: (state) => state.step,
  count: (state) => state.count,
};

const actions = {
  increment({ commit }) {
    commit('increment');
  },
};

const mutations = {
  increment(state) {
    state.count += state.step;
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
};

my-appvue\src\components\CountValue.vue

<template>
  <div>
    <button @click="increment">increment {{ step }}</button>
    <span>total {{ count }}</span>
  </div>
</template>

<script>
export default {
  name: 'CountValue',
  computed: {
    step() {
      return this.$store.getters.step;
    },
    count() {
      return this.$store.getters.count;
    },
  },
  methods: {
    increment() {
      this.$store.dispatch('increment');
    },
  },
};
</script>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?