Vuex状态管理之Mutation的使用详解

mutations状态更新

vuex中的store状态更新唯一方式:提交mutation

Mutation主要包括两部分:

字符串的事件类型(type)

一个回调函数(handler),该回调函数的第一个参数为state
Vuex状态管理之Mutation的使用详解

mutations传递参数

在通过mutations更新数据的时候,我们可能需要携带一些额外的参数
参数被称作mutations是载荷(Payload)

立即学习“前端免费学习笔记(深入)”;

例子:第一个按钮点击counter+5,第二个按钮点击counter+10

App.vue文件

登录后复制

store文件中的index.js文件

  1. mutations: { incrementCount(state, count) { state.counter += count } },

登录后复制

App.vue文件

  1. methods: { addCount(count) { this.$store.commit("incrementCount", count); } }

登录后复制

mutations提交风格

普通提交风格

  1. this.$store.commit("incrementCount", count);

登录后复制

这样提交,如果打印count,得到的是count

  1. incrementCount(state, count) { // state.counter += count console.log(count); }

登录后复制

Vuex状态管理之Mutation的使用详解
特殊的提交风格

  1. this.$store.commit({ type: "incrementCount", count });

登录后复制登录后复制

如果打印count,得到的是一个对象

  1. incrementCount(state, count) { // state.counter += count console.log(count); }

登录后复制

Vuex状态管理之Mutation的使用详解所以在mutations中这样比较合适

  1. incrementCount(state, payload) { state.counter += payload.count console.log(payload.count); }

登录后复制

App.vue中提交

  1. this.$store.commit({ type: "incrementCount", count });

登录后复制登录后复制

mutations响应规则

vuex中的state是响应式的,当state中数据发生改变时,vue组件会自动更新。

当我们改变原有对象中的值时,页面也会发生改变

  1. state: { info: { name: 2401, age: 18 } }, mutations: { // 改变info中的值 infoChange(state) { state.info.age = 10 } },

登录后复制

在App.vue中

  1. {{$store.state.info}}

登录后复制

  1. infoChange() { this.$store.commit("infoChange"); }

登录后复制

Vuex状态管理之Mutation的使用详解
Vuex状态管理之Mutation的使用详解
向原有对象增加值

不能做到响应式的方法

  1. state.info['address'] = '地球';

登录后复制

其实address已经被加到info中了,但是这样的方法做不到响应式,所以在页面上没有显示Vuex状态管理之Mutation的使用详解响应式方法

  1. Vue.set(state.info, "address", '地球');

登录后复制

Vuex状态管理之Mutation的使用详解
删除原有对象中的值

不能做到响应式的方法

  1. delete state.info.age;

登录后复制

其实info中age已经被删除,但是这样的方法做不到响应式,所以页面上还存在age
Vuex状态管理之Mutation的使用详解
响应式方法

  1. Vue.delete(state.info, "age")

登录后复制

Vuex状态管理之Mutation的使用详解

mutations常量类型

官方推荐,将mutations中的方法名都定义为常量,不容易出错,也便于管理维护

在store文件下创建mutations-type.js文件,存放常量

  1. export const INCREMENT = "increment"export const DECREMENT = "decrement"

登录后复制

在store文件下的index.js文件中导入并使用

  1. import { INCREMENT, DECREMENT} from "../store/mutations-type"

登录后复制

  1. mutations: { [INCREMENT](state) { state.counter++; }, [DECREMENT](state) { state.counter--; }, }

登录后复制

在App.vue文件中导入并使用

  1. import { INCREMENT, DECREMENT } from "../src/store/mutations-type";

登录后复制

  1. methods: { add() { this.$store.commit(INCREMENT); }, sub() { this.$store.commit(DECREMENT); }, }

登录后复制

【相关推荐:vue.js视频教程】

以上就是Vuex状态管理之Mutation的使用详解的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
编程技术

Vue详解之增加组件扩展性的slot

2025-4-1 16:59:07

编程技术

深入了解Vue计算属性computed的使用

2025-4-1 16:59:19

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
私信列表
搜索