手把手带你玩转Vuex

102 阅读2分钟

前言

项目中避免不了数据之间的传递,像之前有给大家介绍组件之间的数据传送方式,但是如果有一个数据每个组件都需要用到的话,那么那些传送方式都太太太麻烦了,而且要写的地方很多,这个时候Vuex就起到了至关重要的作用了!

Vuex是什么

vuex是基于vue状态管理的库,简单来说,Vuex可以理解为一个项目中储存数据的仓库,项目的任何一个组件都可以通过这个仓库获取到这个仓库的数据

如何使用Vuex

1. vuex的5个属性

首先咱们先看一张图,没看懂也没关系,接下来我会详细给大家分解一下的!

image.png

  1. State 定义以及储存共享数据,其他组件访问仓库的数据可以通过 this.$store/mapState
  2. Mutatios 修改vuex数据的唯一来源,方便咱们后期的维护以及调试,基本是用来处理同步
  3. Actions: 用来处理异步的操作,但是想修改数据的话还是需要通过Mutatios
  4. Getters: 基于state进行的衍生数据
  5. Module: 将数据开启模块化,方便维护

实际咱们来操作一下,大家可能看上面也感觉还是懂的不够详细吧

//首先项目中得有Vuex
import Vue from 'vue' 
import Vuex from 'vuex' 
Vue.use(Vuex) 
export default new Vuex.Store({ 
state: {
  count:1,
  dataObj:{
    text:"文本",
    text2:"文本2",
  }
}, 
mutations: {
// 两个参数 state playLoad传递进来的参数
  uploadCount(state, playLoad){
    state.count+= playLoad
  }
}, 
actions: {
 increment(context,playLoad){
  context.commit('uploadCount',playLoad)
 },
 //解构的话
 increment2({commit,state}){
   commit('uploadCount')
 },
}, 
getter:{
//接受两个参数  state getters
 getObj(state){
   return state.dataObj.text2
 },
 getNum(state,getters){
    console.log(getters.getObj.length)
    return `数量是${state.conut}`
  }
} 
})
//在mian.js记得注册一下
引入 import store from './store' 
new Vue({ router, store, render: (h) => h(App) }).$mount('#app')
//组件如何获取数据 
//1. 简单 this.$store.state.count  2.使用mapState
import { mapState } from "vuex"
...mapState(['count'])
...mapState({num:'conut'})//改变量改名字

//1. 简单 this.$store.getters.getObj  2.使用mapGetters
import { mapGetters } from "vuex"
...mapGetters(['getObj'])
...mapGetters({num:'getObj'})//改变量改名字

//1. 简单this.$store.commit('uploadCount',10) 2. 使用mapMutations
import { mapMutations } from 'vuex';
methods:{
...mapMutations['uploadCount']
...mapMutations[{changeNum:'uploadCount'}]
}

//1. 简单this.$store.dispatch('increment') 2. 使用mapActions
import { mapActions } from 'vuex';
methods:{
...mapActions['increment']
...mapActions[{changeNum:'increment'}]
}

//模块化的话
const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

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

const store = createStore({
  modules: {
    user: moduleA,
    app: moduleB
  }
})
 
//组件中获取方式 this.$store.state.user

//module
const moduleA = {
  namespaced: true,//开启带命名空间的模块
  state: () => ({
    count: 0
  }),
  mutations: {
    increment (state) {
      // 这里的 `state` 对象是模块的局部状态
      state.count++
    }
  },
  actions:{
  // context 可以结构出  state(局部), commit, rootState(根节点)
    addNum(context){
      return context.commit('increment')
    }
  },
  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  }
}

📢:开启命名空间后的详细的可以查看:vuex.vuejs.org/zh/guide/mo…

Vuex的缺点

Vuex确实好用 但是有一个致命的缺点 数据不能持久化

解决方案

  1. 插件 vuex-persistedstate
  2. LocalStorage
  3. Cookie
  4. SesstionStorage

项目中使用场景

项目中通常都是用户信息,token或者网页的配置数据存入到Vuex

。。。。欢迎大家随时指正!