Vue状态管理工具:vuex

目录

基本概念

使用步骤

核心概念

1.State

2.Getters

3.Mutations

4.Actions

5.Modules

辅助函数

基本概念

基础用法


基本概念

官方:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

简单来说,Vuex 是实现组件全局(数据)管理的一种机制,可以方便的实现组件之间共享数据。可以把它当成一个store仓库,可以集中管理共享的数据,并且存储在vuex中的数据都是响应式的,数据与页面同步。

一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中。


使用步骤

1).安装vuex

npm install vuex --save

2).引用Vuex,并创建 Store仓库

可以在一个单独的文件(如 store.js)中创建 store,并导出它以便在其他地方使用。

import Vue from 'vue';  
import Vuex from 'vuex';  
  
Vue.use(Vuex);  
  
const store = new Vuex.Store({  
  state: {  定义状态  },  
  mutations: {  定义改变状态的方法  },  
  actions: {  定义执行异步操作的方法  },  
  getters: {  定义计算属性  }  
});  
  
export default store;

3).将 Store 挂载到 Vue 实例

import Vue from 'vue';  
import App from './App.vue';  
import store from './store'; // 引入上面创建的 store  
  
new Vue({  
  el: '#app',  
  store, // 将 store 挂载到 Vue 实例上  
  render: h => h(App)  
});

4). 在组件中使用vuex:通过 this.$store 来访问 Vuex store 

created(){
  console.log(this.$store)
}

核心概念

store 仓库将包含state、mutations、actions以及从 state 中派生出一些状态的计算属性getters。

1.State

state提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。当组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会响应式地更新。

const store = new Vuex.Store({
  // state 状态数据
  state: { count: 666 }
})

//组件中访问
this.$store.state
2.Getters

getters允许我们对 Store 中的数据进行加工处理形成新的数据。可以被认为是 store 的计算属性。getters和computed一样具有缓存机制

如:在state.count的基础上派生出一个新的状态newCount出来

const store = new Vuex.Store({
   state:{
      count:666  
   },
   getters:{
      newCount:state => state.count * 3
     // 简化箭头函数(state) => { return state.count * 3 }
   }
});

//组件中获取newCount
this.$store.getters.newCount;
3.Mutations

mutations是唯一更改 store 中状态的方法。mutation必须是同步函数,因为Vuex 的状态跟踪机制依赖于同步的 mutations,当 mutation 异步执行时,Vuex 无法准确地知道何时状态已经更新,这可能导致无法正确地显示状态变化

 const store = new Vuex.Store({
    state:{
        count:666
    },
    mutations:{
        increment(state,value){
            state.count += value;
        }
    }
 });

//组件中调用
//通过commit提交一个名为increment的mutation
this.$store.commit("increment", 需要提交的值);
4.Actions

actions可以包含任意异步操作。Action 类似于 mutation,不同在于:由于异步操作不能直接更新状态,所以Action 提交的是 mutation,而不是直接变更状态。

Action 通过 context.commit 提交一个 mutation,或者通过 context.dispatch 触发其他 action

const store = new Vuex.Store({
  state: {
      count:666
  },
  mutations: {
      changeCount(state, num) {
          state.count = num
      }
  },
  actions: {
    setAsyncCount (context, num) {
      // 一秒后, 给一个数, 去修改 num
      setTimeout(() => {
        context.commit('changeCount', num)
      }, 1000)
    }
  }
})

//组件中调用
//通过dispatch调用一个名为setAsyncCount 的action
this.$store.dispatch('setAsyncCount', 888)
5.Modules

Modules每个模块拥有自己的 state、mutation、action、getter 甚至是嵌套子模块。如果把所有的状态都放在state中,随着项目的复杂化,Vuex会变得难以维护。为了方便管理,一般会将其按功能分割成不同的模块(Module)。

import Vue from 'vue';  
import Vuex from 'vuex';  
import moduleA from './module/moduleA' // 模块A
import moduleB from './module/moduleB' // 模块B

Vue.use(Vuex);  
  
const store = new Vuex.Store({  
  state: { },  
  mutations: { },  
  actions: { },
  getters: { } ,
  modules: {
        moduleA,
        moduleB
    }
});  
  
export default store;

//子模块moduleA/moduleB
// 每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
export default {
    state: {
        text: 'moduleA/moduleB'
    },
    getters: {},
    mutations: {},
    actions: {}
}

//组件调用
this.$store.state.moduleA.text;

辅助函数

基本概念

一般情况下,如果需要访问vuex.store中state存放的数据,需要使用this.$store.state.属性名方式。当一个组件需要获取多个状态时候,将这些状态都声明会有些重复和冗余。为了解决这个问题,辅助函数应运而生。

通过辅助函数把vuex.store中的属性映射到vue实例身上,这样在vue实例中就能访问vuex.store中的属性了,对于操作vuex.store就变得非常方便。

属性辅助函数
statemapState
gettermapGetters
actionsmapActions
mutationsmapMutations

import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'

基础用法

以下均为Vuex的辅助函数提供的语法糖的方式

1. mapState: 将state映射到组件的computed计算属性中。组件可通过访问这些计算属性来直接获取state中的状态值。

import { mapState } from 'vuex';  
  
export default {  
  computed: {  
    ...mapState(['count']) // 将store中的count状态映射到组件的computed属性中  
  }  
}

使用mapState后,在组件的模板中,可以直接使用this.count来访问state中的count状态。

2.mapGetters:将getters映射到组件的computed计算属性中。与mapState类似,这样做可以方便地在组件中通过计算属性来访问getters返回的计算值。

import { mapGetters } from 'vuex';  
  
export default {  
  computed: {  
// 将store中的doneTodos getter映射到组件的computed属性中  
    ...mapGetters(['doneTodos']) 
  }  
}

 3. mapMutations:将mutations映射到组件的methods方法中。这样,组件就可以通过调用这些方法来直接触发mutations,从而修改state中的状态值。

import { mapMutations } from 'vuex';  
  
export default {  
  methods: {  
    // 将store中的increment mutation映射到组件的methods中  
    ...mapMutations(['increment']), 
    addCount() {  
      // 调用increment方法时,会自动触发store中的increment mutation 
      this.increment();  
    }  
  }  
}

4. mapActions:将actions映射到组件的methods方法中。与mutations不同,actions主要用于处理异步操作。通过映射actions,组件可以方便地触发这些异步操作。

import { mapActions } from 'vuex';  
  
export default {  
  methods: {  
    // 将store中的incrementAsync action映射到组件的methods中  
    ...mapActions(['incrementAsync']), 
    addCountAsync() {  
      // 调用incrementAsync方法时,会自动触发store中的incrementAsync action  
      this.incrementAsync(); 
    }  
  }  
}

 若有错误或描述不当的地方,烦请评论或私信指正,万分感谢 😃

  • 23
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值