没有特别的幸运,那么就特别的努力!!!
1.手动利用HTML5的本地存储
vuex的state在localStorage或sessionStorage或其它存储方式中取值
缺点:最直观的就是,手动写比较麻烦。
2.利用vuex-persistedstate持久化插件处理
插件的原理其实也是结合了存储方式,只是统一的配置就不需要手动每次都写存储方法
nuxt 项目解决方案:
1.安装vuex-persistedstate插件
yarn add vuex-persistedstate --save
或
npm install vuex-persistedstate --save
2.新建plugins/vue-persistedstate.js文件
import createPersistedState from 'vuex-persistedstate'
export default ({ store }) => {
createPersistedState({
storage: sessionStorage
})(store)
}
3.配置项nuxt.config.js
plugins: [
{ src: '@/plugins/vue-persistedstate.js', ssr: false }
],
vue项目
1.安装插件
npm install vuex-persistedstate --save
或
yarn add vuex-persistedstate --save
2.引入及配置:在store下的index.js中
使用vuex-persistedstate默认存储到localStorage
import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
state: { ... },
mutations: { ... },
actions: { ... },
plugins: [createPersistedState()]
})
-------------------------------------vuex的使用-----------------------------------------
前提:
1,安装 npm i vuex --save
简略的文件结构 store
src文件
1. store
modules文件
auth.js
common.js
index.js
2.view文件
home.vue
vuex文件
1.auth.js
const state = {
areaList:[]
}
const getters = {}
const mutations = {
infoState (state, payload) {
state.areaList = payload.areaList
},
}
const actions = {
updateArea ({ commit }, payload) {
commit('infoState', payload)
},
}
export default {
state,
getters,
actions,
mutations
}
2.common.js
const state = {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
}
const getters = {
areaOptions (state) {
return state.todos.filter(todo => todo.done)
},
}
const mutations = {
// 设置Token
}
const actions = {
// 更新Token 的方法
}
export default {
state,
getters,
actions,
mutations
}
3.index.js
/* Vuex 模块组装 */
import Vue from 'vue'
import Vuex from 'vuex'
import auth from './modules/auth'
import common from './modules/common'
Vue.use(Vuex)
// 导出 store 对象
export default new Vuex.Store({
// strict: process.env.NODE_ENV !== 'production',
modules: {
auth,
common
},
// plugins: process.env.NODE_ENV !== 'production' ? [createLogger()] : []
})
view文件,运用vuex
home.vue
<template>
<div class="home">
hello world
</div>
</template>
<script>
import { mapGetters , mapActions } from 'vuex'
export default {
name: 'Home',
components: {},
data(){
return{}
},
// 监听属性 类似于data概念
computed: {
...mapGetters(['areaOptions'])
},
created () {},
// 生命周期 - 挂载完成(可以访问DOM元素)
mounted () {
this.updateArea({ areaList: [{ id: 2, text: '...', done: true }] })
console.log(this.areaOptions,this.$store.state.auth)
},
methods: {
...mapActions([
'updateArea'
])
}
}
</script>
希望能帮助到大家,同时祝愿大家在开发旅途中愉快!!!