VueX,VueX持久化

468 阅读2分钟

VueX的作用:

VueX是用来在Vue项目开发中使用的状态管理工具。试想一下,如果在一个项目开发中频繁的使用组件传参的方式来同步data中的值,一旦项目变得很庞大,管理和维护这些值将是相当棘手的工作。为此Vue为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX。在具有VueX的Vue项目中,我们只需要把这些值定义在VueX中,即可在整个Vue项目的组件中使用。 (VueX是单向数据流)

VueX官网: vuex.vuejs.org/zh/

VueX的使用:
在main.js 中引入 store

image.png

image.png

image.png

- state:用来设置值

image.png
在组件中引用在computed(计算属性)中用...mapState结构构正常使用
注意:不能直接修改值,只能调用mutations中的函数进行修改

  import {mapState} from "vuex";
  computed: {
  // 经过解构后,自动就添加到data中,此时就可以直接像访问data一样访问它
  //user 代表是user模块下的,如果没有可以不用写
    ...mapState("user", ["token"]),
  }

- mutations:用来写方法(同步函数)

  mutations: {
      //gettoken是函数名称
      //state代表值VueX中state里面的所用值
      //val传过来的参数
    gettoken(state, val) {
        //给token修改值
        state.token = val.token
    }
  }

在组件中引用在methods中用...mapMutations解构正常使用

        import {mapMutations} from "vuex";
        methods: {
        // 经过解构后,自动就添加到了计算属性中,此时就可以直接像访问计算属性一样访问它
        //user 代表是user模块下的,如果没有可以不用写
        ...mapMutations("user", ["gettoken"])
        
        // 赋别名的话,这里接收对象,而不是数组
        ...mapState({ aliasName: 'name' }),  
        
        }

- actions:用来写函数(异步函数)

    actions: {
        // 增加setNum方法,默认第一个参数是context,其值是复制的一份store
        //val代表的参数
        gettoken(context,val) {
          console.log(content)
          context.state.token = '456'
        }
    }

- getters:修饰器

在store文件中写入getters

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: "123"
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  },
  getters: {
    getMessage(state) {
      return `hello${state.token}`
    }
  }
})

在组件中引用在computed(计算属性)中用...mapGetters结构正常使用

    import {  mapGetters } from "vuex";
    computed: {
    // 经过解构后,自动就添加到data中,此时就可以直接像访问data一样访问它
    ...mapGetters(["getMessage"])
  },

- modules:合并模块

Vuex 允许我们将 store 分割成模块(module) 。每个模块拥有自己的 state、mutation、action、getter

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

VueX持久化:

链接:Vuex持久化插件-解决刷新数据消失的问题 (juejin.cn)

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({ 
    //  存储到sessionStorage
   plugins: [createPersistedState({ 
       storage: window.sessionStorage
   })]
})