一、什么是vuex
- vuex :是一个专为vue.js开发的状态管理器,采用集中式存储的所有组件状态
- 五个属性: state、getters、mutations、actions、module
-
基本使用:
新建store.js文件,最后在main.js中引入,并挂载到实列上
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = {} const getters = {} const mutations = {} const actions = {} export default new Vuex.Store({ state, getters, mutations, actions })
- state属性: 存放状态,例如你要存放的数据
- getters: 类似于共享属性,可以通过this.$store.getters来获取存放在state里面的数据
- mutations: 唯一能改变state的状态就是通过提交mutations来改变,this.$store.commit()
- actions: 一步的mutations,可以通过dispatch来分发从而改变state
二、数据持久化
- vuex里面存放的数据,页面一经刷新会丢失:
解决办法: 存放在localStorage或者sessionStorage里面,进入页面时判断是否丢失,丢失再去localStorage或者sessionStorage里面取;
在app.vue根组件的created里面判断是否丢失,在进行上面的操作; -
vuex-persistedstate 插件
cnpm i vuex-persistedstate -S
之后在store.js里面导入
import createPersistedState from 'vuex-persistedstate' export default new Vuex.Store({ state, getters, mutations, actions, plugins: [createPersistedState()] )}
这样的话就可以做到数据持久化啦
三、map辅助函数
- mapActions:
在组件内导入import { mapActions } from 'vuex'
- mapGetters
import { mapGetters} from 'vuex'
其他的mapState,mapMutations也是一样操作
参考链接: vuex数据持久化插件
vuex官网以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 使用IndexedDB做前端日志持久化
- 011.Kubernetes使用共享存储持久化数据
- 在DDD中使用MongoDB作为持久化
- iOS 数据持久化方案-Realm的使用
- iOS数据持久化:使用NSKeyedArchiver进行数据归档
- 使用Go构建区块链 第3部分:持久化和cli
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Understanding Computation
Tom Stuart / O'Reilly Media / 2013-6-3 / USD 39.99
Finally, you can learn computation theory and programming language design in an engaging, practical way. Understanding Computation explains theoretical computer science in a context you'll recognize, ......一起来看看 《Understanding Computation》 这本书的介绍吧!