vuex的 State ,Mutation ,Action ,Getter ,Module用途,关系

描述一下vuex的 State ,Mutation ,Action ,Getter ,Module用途,关系,
分别举例说明他们如何使用。

1.存储数据 State 全局数据 只要一更改,所有使用的地方都会发生改变
2.改变数据(同步)Mutation 通过 提交 commit 来更改 State
3.改变数据(异步)Action 不能直接更改 需要通过 Mutation
4.计算数据 Getter 计算属性 对 State 的更改 仅在使用处,不影响全局
5.模板数据 Module 包含一套完整的 State,Mutation,Action,Getter,
可存在多个 Module 每个 Module 的 State,Mutation,Action,Getter 都是独立的

因为  Mutation  中只能是同步操作,但是在实际的项目中,会有异步操作; 那么  Action  就是为了异步操作而设置的。这样,就变成了在 Action 中去提交 Mutation然后在组件的  methods  中去提交  Action ;  只是提交 Action 的时候使用的是 dispatch 函数,而 Mutation 则是用 commit 函数。

 五个部分并不是必须的,需要用到什么就添加什么。
 但是一般再怎么简单的 Vuex,也至少会由 State 和 Mutation 构成

// 调用 获取 改变数据
// wx/getAppid 从 vuex 中调用 指定方法
// 在 vuex 中需要 dispatch 来触发 actions 中的方法
store.dispatch(“wx/getAppid”, { domain: window.location.href }).then((res)=>{
// 输出
console.log(res)
})

// 展示 数据
//

{{ wx.appid }}


// 导入
// import { mapState } from “vuex”
// computed: {
// …mapState({
// wx: (state) => state.wx
// })
// }

// 仓库 存储 改变数据
// 导入
import { getAppid } from “@/api/index”;
// 存放状态 全局变量
const state = {
appid: “”,
}

// state的计算属性 通过getter中的方法来获取state值
// 调用
// this.$store.getter.getappid
const getter ={
getappid(state){
return “APPId为:”+ state.appid
},
}
// 更改state中状态的逻辑,同步操作
const mutations = {
SET_APPID: (state, appid) => {
state.appid = appid;
},
}

// 提交mutation,异步操作
const actions = {
getAppid({ commit }, data) {
return new Promise((resolve, reject) => {
// 方法
getAppid(data)
.then((res) => {
// 修改数据 actions 中的 commit 可以触发 mutations 中的方法
// state 的值只能通过 mutations 来修改
commit(“SET_APPID”, res.data.app_id);
// 将结果传递到调用的地方 否则调用的then没有输出
resolve(res);
})
.catch((err) => {
console.log(“失败”);
reject(err);
});
});
},
}

// Module
// module 是为了将store拆分后的一个个模块,方便管理。
// 一个项目可存在多个 Module
// 每一个 module 中都会有一套专属的 state getters mutations actions
// const module = {
// state: {},
// getters: {},
// mutations: {},
// actions: {}
// }

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1

不用下md?这代码看起来有点乱

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!