我使用npm install --save vuex-persistedstate安装了持久状态。
然后我像这样设置我的Vuex store.js文件:
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
title: ''
},
mutations: {},
actions: {},
getters: {},
plugins: [createPersistedState()]
})
..然后在另一个组件中,我将值传递给store.title:
this.$store.state.title = this.input
它有效。
但是在刷新页面(F5)之后,this.input
不再存储在this.$store.state.title
中,这破坏了我的站点功能。
我在做什么错了?
编辑:我确实可以使用香草风格:
第一:
this.$store.state.title = this.input
localStorage.setItem('title', this.$store.state.title)
然后:
mounted () {
this.$store.state.title = localStorage.getItem('title')
}
仍然想知道为什么Vuex插件不起作用:(
答案 0 :(得分:0)
您可以尝试应用以下代码
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
title: ''
},
mutations: {},
actions: {},
getters: {},
plugins: [createPersistedState({
key: 'keyname',
storage: window.localStorage
})]
})
在“ createPersistedState”内部,可以将路径以及“ paths:['accessRights']”设置为另一个属性。如果您不提供路径,那么整个状态将是持久性的
答案 1 :(得分:0)
我正在使用#vuex存储模块,这对我的#vue #vuex #laravel应用程序很有效,它可以使用#vuex-persistedstate持久存储状态。如果您不使用HTTPS,请执行更多操作,然后将安全性设置为false。
import createPersistedState from 'vuex-persistedstate';
import Cookies from 'js-cookie';
Vue.use(Vuex);
export default new Vuex.Store({
strict:true,
modules:{
party,
contract
},
plugins: [createPersistedState(
{
paths:['party.selectedParty','contract.contracts',
'contract.partyId',
'contract.partyContracts',
'contract.selectedContract',
],
storage: {
getItem: key => Cookies.get(key),
setItem: (key, value) => Cookies.set(key, value, { expires: 3,
secure: false }),
removeItem: key => Cookies.remove(key)
},
}
)],
});
答案 2 :(得分:-2)
看起来只有完成commit
的呼叫:
index.js`:
import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
plugins: [createPersistedState()],
mutations: {
increment: state => state.count++,
decrement: state => state.count--
}
});
new Vue({
el: "#app",
computed: {
count() {
return store.state.count;
}
},
methods: {
assign() {
store.state.count = 4;
},
increment() {
store.commit("increment");
},
decrement() {
store.commit("decrement");
}
}
});
index.html
<div id="app">
<p>{{ count }}</p>
<p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</p>
<p>
<button @click="assign">Assign 4</button>
</p>
<small>
Check out your localStorage to see the updates.
</small>
</div>
package.json
{
"name": "vuex-persistedstate",
"version": "1.0.0",
"description": "Basic example of the vuex-persistedstate plugin",
"keywords": ["vue", "vuex", "vuex-persistedstate"],
"main": "index.js",
"dependencies": {
"vue": "2.5.22",
"vuex": "3.1.0",
"vuex-persistedstate": "2.5.4"
}
}
https://codesandbox.io/embed/vuex-persistedstate-fhb4o?fontsize=14&hidenavigation=1&theme=dark