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

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

一、什么是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 Machine Learning

Understanding Machine Learning

Shai Shalev-Shwartz、Shai Ben-David / Cambridge University Press / 2014 / USD 48.51

Machine learning is one of the fastest growing areas of computer science, with far-reaching applications. The aim of this textbook is to introduce machine learning, and the algorithmic paradigms it of......一起来看看 《Understanding Machine Learning》 这本书的介绍吧!

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

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试