Vuex是什麼 主要用來做什麼 為什麼要使用vuex

本文详细解析了Vue.js的官方状态管理库Vuex的工作原理,包括其五大核心属性state、getter、mutation、action和module的功能及使用场景,通过实例展示了如何在Vue项目中有效管理和维护复杂状态。

一、Vuex是什麼

  1.   Vuex是一個大管家,多個組件共享的變量全部存儲在一個對象裡
  2. 將這個對象放在頂層vue實例中,讓其他組件使用,如下圖為多頁面

二、Vuex的五個屬性

  • state:vuex的基本數據,用來儲存變量
  • getter:從基本數據(state)派生的數據 ,相當於state的計算屬性(computed)
  • mutation:提交更新數據的方法,必須是同步,美國mutation都有一個字符串事件類型(type) 和回調函數(handler)
  • action:和mutation的功能大致相同,不同之處在於(action提交的是mutation,不是直接變更狀態;action包含任意異步操作)
  • module:模塊化vuex,可以讓每一個模塊擁有自己的state,mutation,action,getters

 

三、Vuex狀態管理開發

    3.1  state & mutations

npm install vuex --save
//store文件夾下  新增index.js

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


Vue.use(Vuex)

const store = new Vuex.Store({//Vuex.Store
  state: {//管理的状态对象
    counter: 1000,
   
  },
  mutations: {//只能包含同步的代码, 不能写异步代码
    increament(state) { 
      state.counter ++;
    }
  }
})


export default store


//在main.js全局註冊
import Store from './components/store/index'
new Vue({
  el: '#app',
  router: router,
  i18n: '',
  Store,
  components: { App },
  template: '<App/>',
 
})


//在使用的頁面

<button @click="addition">+</button>
<p>{{$store.state.counter}}</p>


computed:{
      counter:function(){
          return this.$store.state.counter
      }
  },
methods:{
      addition(){
          this.$store.commit('increament')
      }
}

3.2 getters相當於state的計算屬性(computed)

 

state: {
     student:[
      { id: 111, name: "kk", age:18 },
      { id: 121, name: "kko", age:28 },
      { id: 131, name: "kkoo", age:38 },
      { id: 141, name: "kkpo", age:8 },
    ]
   
  },

getters: {
    
    more20Stu(state) { 
//找出大於18歲的數據
      return state.student.filter(s => s.age >  18)
    },
    
  }

mutation 只能通過其他方式來更新屬性未定義的內容

//在使用的地方

<p>{{$store.state.info}}</p>
<button @click="addInfo">更新用戶</button>


addInfo(){
          this.$store.commit('upInfo')
      },



//index.js

info: {
     id:151,name:"kkk",age:35
   }

upInfo(state) { 
      Vue.set(state.info,'address','los')
      Vue.delete(state.info,'age')

    }

3.3 mutation提交更新數據的方法,必須是同步,如下為異步,就無法做到響應式


    increament(state) { 
       setTimeout(()=>{
         state.counter++;
         },1000)
    },

3.4 actions(為了解決異步如上圖頁面顯示和數據不同步的問題,將actions   dispatch 給mutation更新)

//index.js
actions: {//異步操作
    aUpdateInfo(context,payload) { 
      setTimeout(() => { 
        context.commit('upInfo');
        payload.success();
        payload.message
      },1000)
    }
  }
upInfo(state) { 
      Vue.set(state.info, 'address', 'los');
      
    }


//在使用地方

<button @click="updateInfo">更用戶</button>

updateInfo(){
          this.$store.dispatch('aUpdateInfo',{
              message:"message",
              success:()=>{
                  console.log('ok')
              }
          })
      },

 

3.5 mutation 常量類型


//index.js

mutations: {//只能包含同步的代码, 不能写异步代码
    increament(state) { 
      state.counter ++;
    }
}


//mutation-types.js 導出
export const INCREAMENT = 'increament'


//使用地方引用
import {INCREAMENT} from './store/mutation-types'

 addition(){
          this.$store.commit(INCREAMENT)
      },

3.6 module (模塊)  vuex 允許我們將store分割成大大小小的對象,每個對象擁有自己的state,getter,action,mutation,這個對象叫module

const moduleA={
  state: {count:0 },
  getters: { fiveCount(state) {
    return state.count + 5
  }
  },
  mutations: { 
    increment(state) {
      state.count++
    }
  },
  actions: {
    ifcrementRootSum({state,commit,rootState }) {
      if ((state.count - rootState.count) * 2 === 1) {
        commit('increment')
      }
    }
   }
}

export default moduleA




//使用的地方引用
import moduleA from './module/moduleA';

export default new Vuex.Store({
    modules: {
        moduleA
    },
    // ...
}

 

<think>嗯,用户问的是Vuex中actions和mutations的主要区别。我需要先回忆一下Vuex的基本概念。Vuex是Vue的状态管理库,核心包括state、getters、mutations、actions。mutations和actions都用于改变状态,但它们的职责不同。 首先,mutations是同步的,用来直接修改state。每个mutation都有一个字符串类型的事件类型和一个回调函数,回调函数里进行实际的修改。而actions可以包含异步操作,通常通过提交mutations来改变状态。也就是说,actions不直接修改state,而是提交mutation。 然后,触发方式也不同。mutations需要用commit来触发,而actions用dispatch。比如在组件中,this.$store.commit('mutationName')和this.$store.dispatch('actionName')。 另外,actions可以处理异步操作,比如API调用,完成后提交mutation。而mutations必须是同步的,确保状态变更可追踪。 举个例子,用户登录时,可能需要异步请求验证,这时候用action调用API,获取数据后commit一个mutation来更新state中的用户信息。 可能用户需要具体代码示例,比如一个action里调用setTimeout模拟异步,然后commit。而mutation直接修改state。 然后要考虑为什么这样设计。因为同步的mutations让状态变更可追踪,devtools可以记录每次state的变化,而异步操作如果在mutation里会导致状态变化难以追踪。 接下来要回答主要区别,分点说明,同步异步、触发方式、职责不同。然后给出示例代码,比如mutations里的同步方法和actions里的异步方法。 最后,相关问题要围绕Vuex的其他概念,比如为什么需要分actions和mutations,如何传递参数,模块化中的区别,以及如何组合多个action。</think><< Vuex中actions和mutations的主要区别如下: ### 1. **职责不同** - **Mutations**: 唯一允许直接修改`state`的入口,必须是同步操作。 ```vue // store.js mutations: { increment(state, payload) { state.count += payload.amount; } } ``` - **Actions**: 负责处理业务逻辑(尤其是异步操作),通过提交`mutation`间接修改`state`。 ```vue // store.js actions: { asyncIncrement({ commit }, payload) { setTimeout(() => { commit('increment', payload); }, 1000); } } ``` ### 2. **触发方式不同** - **Mutations**:通过`commit`触发。 ```vue this.$store.commit('increment', { amount: 10 }); ``` - **Actions**:通过`dispatch`触发。 ```vue this.$store.dispatch('asyncIncrement', { amount: 10 }); ``` ### 3. **异步与同步** - **Mutations**:必须是同步操作(否则会导致状态追踪失效)。 - **Actions**:可以包含异步操作(如API请求、定时任务)。 ### 原因解释 Vuex通过强制`mutations`为同步操作,确保`state`变更可被DevTools准确追踪(如时间旅行调试)。`actions`的异步特性则支持复杂业务逻辑的封装,同时保持代码结构清晰。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值