Mutations与Actions有什么区别
vuex的mutations与actions有什么区别,除了用法上mutation是同步,actions是异步,这里的同步与异步指的是commitordispatch?并不是,同步指mutations方的内部是同步的,而actions内部可以是异步的,并且修改数据只能在mutations中修改,在actions中异步的操作副作用是通过mutations来记录
我们修改数据就是$store.commit('eventName', parameters),当我们触发commit时,实际上是已经在异步请求回调里获取了数据。
但是官方在描述mutation有这么说,mutation内部必须是同步函数,异步会导致内部状态难以追踪,devtool难以追踪state的状态
也就是说当我们在mutations中的appIsShow中使用了异步函数,我们在$store.commit('appIsShow')时,很难追踪state的状态,因为在触发commit事件时,异步的回调函数不知道什么时候执行,所以难以追踪。
mutations是同步事务,假设在mutations有多个异步的调用,你很难确定这些异步哪些先执行,很难追踪state的变化,所以也给调试带来了一定难度
话说回来,这么写也确实是可以做到更新state的值,如果我不用vuetool这个工具,貌似也没毛病
既然mutations是同步的事情,那么异步官方就使用了actions方案
actions里面可以做异步操作,但是并不是直接修改数据,提交的是mutations里面的方法
使用案列:
/src/store/index.js状态管理器
import axios, { Axios } from 'axios';
import { CHANGE_APPISSHOW } from './type.js'
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
appIsShow: true,
datalist: [],
}
},
//同步
mutations: {
changeAppIsShow(state, boolParams) {
state.appIsShow = boolParams;
},
dataListInit(state, arrParams) {
state.datalist = arrParams;
}
},
//异步+同步:action不能直接修改state()中的数据,它是也是向mutations提交数据来修改的。
actions: {
async getDataList(store) {
//异步
const result = await axios({
url: "https://m.maizuo.com/gateway?cityId=110100&ticketFlag=1&k=3777796",
headers: {
'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.1","e":"16992764191480200349024257","bc":"110100"}',
'X-Host': 'mall.film-ticket.cinema.list'
}
});
//同步:向mutations提交数据:触发dataListInit函数,并向函数传递了一个数组参数
store.commit("dataListInit", result.data.data.cinemas);
}
}
});
export default store
main.js:注册状态管理器
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
//import store from "../src/store" //状态管理器js 注意:如果仅仅是指定了一个文件夹router,程序会自动去router文件夹下寻找index.js,并导入
//import store from "../src/store/index" //导入状态管理器js 注意:.js可以省略
//import store from "../src/store/myindex.js" //导入状态管理器js 注意:如果我们的状态管理器文件不是index.js 那么我们就得指定具体的名称了
import store from "../src/store/index.js" //导入状态管理器js
var app=createApp(App)
app.use(store) //注册vuex插件:状态管理器
app.mount("#app")
组件中使用
<template>
<div>
<ul>
<li v-for="item in $store.state.datalist" :key="item.cinemaId">{{item.name}}</li>
</ul>
</div>
</template>
<script>
export default {
mounted(){
if(this.$store.state.datalist.length===0){
//如果数据为空,则去触发actions的中的getDataList方法,达到获取datalist数据的目的。而this.$store.state.datalist中的数据存在内容中,其他地方需要这个数据直接从内存中取,相当于有个缓存,
this.$store.dispatch("getDataList");
}
}
}
</script>