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.

Vue.js Vuexで状態を管理する (値を永続化して保存する)

Last updated at Posted at 2022-01-01

前回(https://www.mkhs.work/wordpress2/?p=223)で、値を設定しましたが、再描画すると値はクリアされてしまいました。storeで設定した値は永続化されていませんでした。

永続化するために、vuex-persistedstate(プラグイン)を使います。インストールします。

[root@localhost hell_app]# npm install  vuex-persistedstate
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/webpack-dev-server/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/watchpack-chokidar2/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

vuex-persistedstate@4.1.0
added 3 packages from 2 contributors and audited 1345 packages in 16.238s

92 packages are looking for funding
run npm fund for details
found 14 vulnerabilities (10 moderate, 4 high)
run npm audit fix to fix them, or npm audit for details

store.jsへ vuex-persistedstateを組み込みます。store.jsを修正します。コンポーネントは修正不要です。

import { createStore } from 'vuex'
// vuex-persistedstate を追加
import  createPersisted from 'vuex-persistedstate'
export const store = createStore({
state() {
return{
message: 'store dataです!!',
counter: 0,
}
},
mutations: {
count_plus: (state) => {
state.counter++
},
count_reset:(state) => {
state.counter = 0
}
},
//追加
plugins: [
createPersisted()
]
})

ブラウザで実行、再描画しても値が保持されている事を確認できます。

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?