VUEX的使用

Vuex是什么?

状态管理模式;采用集中式存储管理应用的所有组件状态;
它有五个属性:state、getters、mutations、actions、modules

1. state

类似于组件中的data,存放数据。

直接使用 this.$store.state.name1=‘我修改了vuex中的state-name1’ 这种方式来直接修改state中的数据,控制台没有报错。但是不建议直接修改;原因:1.如果我们将vuex的模式改为严格模式时,(strict:true)直接修改state中的数据,控制台就会报错。2.如果是多个模块需要引用一个state,每个人都直接修改,可能会造成数据混乱

因此,我们需要通过commit提交mutations的方式来修改state,这样vue的调试工具能够记录每一次state的变化,方便调试。

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  strict:true,
  state: {
   name1:'我是vuex-index的name1',
   name2:'我是vuex-index的name2',
  },
})

组件中使用 this.$store 获取到vuex中的store对象实例,可通过state属性属性获取name1

<template>
  <div class="box">
    <div>{{$store.state.name1}}</div>
    <div class="dianwo" @click="dianwo">点击我</div>
  </div>
</template>
<script>
export default {
methods:{
  dianwo(){
  console.log( this.$store.state.name1)
  },
},
</script>

使用 mapState 辅助函数获取vuex中的state数据

  1. 导入mapState import { mapState } from 'vuex'
  2. 使用扩展运算符将state中的数据映射给计算属性
 computed: {
 // 方法一
    ...mapState(['name1'])
  // 方法二
  name1:(state)=>{return state.name1},
  name2:(state)=>{return state.name2}
  }

2. mutations

类似于组件中的method,用于变更Store中的数据,集中监控所有数据的变化,不能写异步的操作方法。

export default new Vuex.Store({
  state: {
   name1:'我是vuex-index的name'
  },
  mutations: {
    updateName1(state,params){
    // 第一个参数是 state中的数据,第一个参数是传递过来的数据
      console.log('state,params:',state,params);
    }
  },
})

调用 mutations 中的函数

methods:{
  clickMe(){
    this.$store.commit('updateName1','我是点击后修改的数据')
  },
},

辅助函数调用 mutations 中的函数

import { mapMutations } from 'vuex 
methods:{
// 方式一
...mapMutations(['clickMe','clickMe1'])
// 方式二
...mapMutations({
	clicks:'clickMe'
})
}

3.actions

提交mutations的,而不是改变状态,包含任何的异步操作

export default new Vuex.Store({
  state: {
   name1:'我是vuex-index的name'
  },
  mutations: {
    updateName1(state,params){
      console.log('state,params:',state,params);
    }
  },
  actions:{
    actionsName(store,params){
    // 第一个参数包含:commit、dispatch、getters、state、rootGetters、rootState
    // 第二个参数是传递过来的数据
      console.log('actionsNamestore,params:',store,params);
      store.commit('updateName1')
    }
  },
})

使用$store.dispatch调用actions中的函数

methods:{
  dianwo(){
    this.$store.dispatch('actionsName','我是在组件调用的时候传过来的数据')
  },

使用辅助函数调用actions中的函数

import { mapActions } from 'vuex'
methods:{
// 方法一
 ...mapActions(['actionsName'])
 //方法二
  ...mapActions({
  actionsname:'actionsName'
  })
}

4. getters

类似于组件中的computed,对store中的数据进行加工处理形成新的数据,不会修改state中原有的数据,state中的数据变化getter的数据也变化

注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

export default new Vuex.Store({
state: {
   list:[1,2,3,4,5,6]
  },
getters:{
 filterList(state){
      return state.list.filter(item=>item>4)
    }
}
})

调用getters中的方法一

methods:{
  clickMe(){
   console.log( this.$store.getters.filterList);
  },
},

使用辅助函数调用getters中的方法

import { mapGetters } from 'vuex'
export default {
  computed: {
  //方式一
    ...mapGetters(["filterList"])
    //方式二
      ...mapGetters({
      filterlist:filterList
      })
  }
}

5.modules

将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}
// 调用
store.state.a.XX
store.state.b.XX

使用modules我更喜欢新建一个js文件

moduleA.js
export default {
  state: {
    VuexdataName:'我是vuex中的data'
  },
  getters: {
   
  },
  mutations: {
    
  },
  actions: {
    
  },
  modules: {
   
  }
}

引入到index.js文件中

import Vue from 'vue'
import Vuex from 'vuex'
import user from "./user";
import moduleA from "./moduleA";
Vue.use(Vuex)
export default new Vuex.Store({
  modules:{
    user,
    moduleA 
  }
})

在组件中使用:

1 this.$store.state.moduleA.VuexdataName
2. 使用辅助函数
 import { mapState } from 'vuex
 computed:{
 ...mapState({VuexdataName:state=>state.moduleA.VuexdataName})
 }

vuex如何做持久化存储

vuex作为状态管理,相当于全局的变量存储,可以在所有的vue组件中共享、修改数据,它是单向数据流,变量都是响应式的数据;但是当我们刷新浏览器的时候,store中的状态会被清空,回到初始化状态。

1.使用sessionStorage或者localStorage存储

具体使用哪个,看业务需求,我这里使用的是localStorage,将存储的方法简单封装一下,或者直接存储都是可以的,这个看个人喜欢

export default {
  get:key => {
    return JSON.parse(window.localStorage.getItem(key))
  },
  set:(key, value) => {
    window.localStorage.setItem(key, JSON.stringify(value))
  },
  remove:key => {
    window.localStorage.removeItem(key)
  }

在vuex中使用:

import localUtils  from '@/utils/index.js' 
export default {
  state: {
    count: localUtils.get('count') || 0
  },
  mutations: {
    localUtilText(state, count) {
      state.count++
      localUtils.set('count', state.count)
    }
  }

2.使用第三方插件

  1. 安装 npm install vuex-persistedstate
  2. 使用

import Vue from "vue";
import Vuex from "vuex";
import test from './modules/test'
import user from './modules/user'
// 引入插件
import createPersistedState from "vuex-persistedstate";
 
Vue.use(Vuex);
 
export default new Vuex.Store({
  modules: {
    test,
    user
  },
  /* vuex数据持久化配置 */
  plugins: [
    createPersistedState({
      // 存储方式:localStorage、sessionStorage、cookies
      storage: window.localStorage,
      // 存储的 key 的key值
      key: "store",
      //1. 存储了state中所有的数据
      reducer(state) {    
        return { ...state };
      }
      //2. 如果要存储的是某一个模块的数据
      paths:['test']
    })
  ]

state中的变量重名怎么办?

使用modules分模块管理,开启命名空间,用来区分不同模块的数据

modules:{
m1:{
namespaced:true,//开启命名空间
state:{name :'我是m1'},
mutations:{ loginM(){} }
actions:{ loginA(){} 
}
}.

使用:
this.$store.state.m1.name
this.$store.commit('m1/loginM')
this.$store.dispatch('m1/loginA')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值