Vuex笔记-state与mutations的使用

本文详细介绍了如何在Vue项目中使用Vuex的state和mutations管理单一状态树,包括state的定义、mutations的提交与使用方法,并通过实例代码展示了如何在App.vue中操作counter和students数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

Vuex笔记-state与mutations的使用


一、state

1、Vuex使用单一状态树,即每个项目仅包含一个store实例

2、子模块将放置在store实例的modules中

3、state的使用方式类似vue实例中的data,例如:

// store/index.js
const state = {
  counter: 0,
  students: [
    {id: 110, name: 'Elsa', age: 18},
    {id: 111, name: 'Anna', age: 17},
    {id: 112, name: 'John', age: 30},
    {id: 113, name: 'Olaf', age: 6},
  ]
}

const store = new Vuex.Store({
  state,
  mutations: {}
})

二、mutations

1、更改Vuex中store实例的state的方法是提交mutation

2、mutations的使用方法类似于vue实例的methods

3、mutations中的函数默认第一个参数为state

4、使用this.$store.commit()对mutaions函数进行提交

注:mutations中的函数必须是同步的,异步函数在actions中实现

在这里插入图片描述

图片来源:https://vuex.vuejs.org/zh/

二、实际代码

1.新建mutations.js

在这里插入图片描述
mutations代码如下:

export default {
  // 默认第一个参数为state
  increment(state) {
    state.counter++
  },
  decrement(state) {
    state.counter--
  },
  decrementCount(state, payload) {
    // 1.普通提交的接收参数
    state.counter -= payload
    console.log('decrementCount打印的payload = ', payload);
  },
  incrementCount(state, payload) {
    // 2.特殊提交的接收参数
    state.counter += payload.count
    console.log('incrementCount打印的payload = ', payload);
  }
}

2.store/index.js中导入mutations

store/index.js代码如下:

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

import mutations from "@/store/mutations";

// 1.安装插件
Vue.use(Vuex)

// 2.创建对象
const state = {
  counter: 0,
  students: [
    {id: 110, name: 'Elsa', age: 18},
    {id: 111, name: 'Anna', age: 17},
    {id: 112, name: 'John', age: 30},
    {id: 113, name: 'Olaf', age: 6},
  ]
}

const store = new Vuex.Store({
  state,
  mutations
})

// 3.导出store对象
export default store

3.App.vue

App.vue代码如下:

<template>
  <div>
    <h2>counter = {{$store.state.counter}}</h2>
    <button @click="add">+</button>
    <button @click="sub">-</button>
    <button @click="addCount(10)">+10</button>
    <button @click="subCount(10)">-10</button>
  </div>
</template>

<script>

export default {
  name: 'App',
  methods: {
    add() {
      this.$store.commit('increment')
    },
    sub() {
      this.$store.commit('decrement')
    },
    subCount(count) {
      // 1.普通的提交封装
      this.$store.commit('decrementCount', count)
    },
    addCount(count) {
      // 2.特殊的提交封装
      this.$store.commit({
        type: 'incrementCount',
        count
      })
    }
  }
}
</script>

<style>
</style>

三、演示效果

在这里插入图片描述


总结

Vuex笔记-state与mutations的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值