是为vue.js设计的集中式状态管理框架,vuex应用的核心就是store(仓库)。"store"本来就是一个仓库,它包含应用中大部分的状态(state),简单来说就是组件共享data中需要共同的属性。store本身就是一个对象,vue有且只有这一个对象。 vuex和单纯的全局对象有以下两点不同: 1.vuex的状态存储是响应式的。 2.不能直接改变store中的状态,改变store中的状态的唯一途径就是显示的提交((commit)mutation。
1.在src文件下新建store文件,引入vue,vuex,创建store实例。为了方便看,store四个属性没有分开导,这里也没有对store拆分模块。
2在mian.js引入store,并挂载 3获取state有两种方式
this.$store.state.name…mapState映射4改state中的数据,有四种方式,commit,dispatch,mapMutations,mapActions辅助函数
1.commit mutations(直接触发mutaions)
2.使用action,(store使用dispatch通过action触发mutations)
3.使用mapMutations,mapActions辅助函数
目录结构 在外层的模块引入子模块 子模块
vuex的数据是存储在内存中,页面刷新,会丢失数据 总结了以下几种方式 1.手动利用HTML5的本地存储 localStorage或sessionStorage 2.利用vuex-persistedstate插件,原理也是运用本地缓存
npm install vuex-persistedstate --save import Vue from 'vue'; import Vuex from 'vuex'; import createPersistedState from "vuex-persistedstate" Vue.use(Vuex) const store = new Vuex.Store({ state: { name: '', password: '' }, getter: {}, mutations: { setName(state,name) { state.name = name }, }, actions: { actionsSetName(context,value) { context.commit('setName',value) } }, plugins: [createPersistedState({ storage: window.localStorage })] }) export default store js-cookie插件 下载 npm install js-cookie --save引入
import Cookies from 'js-cookie' Cookies.set('name', 'value',{ expires: 7, path: '' }); //7天后过期 Cookies.get('name'); //获取 Cookies.remove('name') //移除 //存对象 const user = { name: '小鹿Max', age: 18 } Cookies.set('user', user) const liaUser = JSON.parse(Cookies.get('user'))最后,源码地址,如有任何问题,还请多指教。