Vuex入门(二)—— mutations详解

目录

知识不足的地方赶快点击学习呦~~~

Vuex入门(一)—— state,mapState,…mapState对象展开符详解
Vuex入门(二)—— mutations详解
Vuex入门(三)—— getters,getters,…getters对象展开符详解
Vuex入门(四)—— action和…mapActions详解
Vuex入门(五)—— 封装module全网最全详解(带源码)
Vuex入门(六)——mapState, mapGetters, mapMutations, mapActions全网最全详解终结篇(带源码)

Vuex官网:https://vuex.vuejs.org/zh/guide/#%E6%9C%80%E7%AE%80%E5%8D%95%E7%9A%84-store

1.store.js

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库

Mutation和Action对比总结:

1.Mutation是同步的,Action是异步的;
2.Mutation是直接变更状态,Action提交的是mutation;
3.Actions和Mutation 都支持载荷方式和对象方式进行分发。

mutations传参state

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {      //  类似于 data
    count: 1,
  },
  mutations: {  //  类似于计算属性  computed
    increment(state) {    //  把上面state对象当参数传入,取对象里面的进行操作
      state.count++
    },
    decrement(state) {
      state.count--
    },
  },
  getters:{
  },
  actions: {},
  modules: {}
})

2.mutations.vue组件mutations详解 + 图片

<template>
  <div>
    <h1>mutations的用法</h1>
    <div style="display: flex">
      <button style="width: 50px" @click="increment">+</button>
      {
   
   { count }}
      <button style="width: 50px" @click="decrement">-</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  computed: {
    count() {
      return this.$store.state.count; //  接收store.js里面的state下面的count        // 语法: this.$store.state.XX   XX为state下面的名称key
    },
  },
  methods: {
    increment() {
      this.$store.commit("increment"); //  接收store.js里面的mutations下面的increment方法   // 语法: this.$store.commit("XX"); XX 为mutations里面自定义函数名
    },
    decrement() {
      this.$store.commit("decrement"); //  接收store.js里面的mutations下面的decrement方法
    },
  },
};
</script>

如下图

在这里插入图片描述

感觉文章好的话记得点个心心和关注,有错的地方麻烦指正一下,多谢!!!

猜你喜欢

转载自blog.csdn.net/m0_49714202/article/details/123474149
今日推荐