Vuex的使用,以及数据持久化

栏目: 编程语言 · 发布时间: 5年前

一、什么是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的使用,以及数据持久化

    Vuex的使用,以及数据持久化

二、数据持久化

  • 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'

    Vuex的使用,以及数据持久化

  • mapGetters import { mapGetters} from 'vuex'

    Vuex的使用,以及数据持久化

其他的mapState,mapMutations也是一样操作

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Understanding Computation

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》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器