Vuex快速入门

本文详细介绍了Vuex的状态管理模式,包括如何安装和创建store,以及State、Mutations、Actions、Getters的使用方法。重点阐述了State作为公共数据源,Mutations用于安全地变更状态,Actions处理异步任务,Getters对状态进行计算处理。此外,还讲解了如何通过Modules进行模块化管理,提高代码组织的清晰度。

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

vuex学习笔记

一、介绍

1.概念

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。 是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。

在这里插入图片描述

2.Vuex的基本使用

1.安装vuex依赖包

npm install vuex --save

2.导入vuex包、创建store对象。(store/index.js)

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules,
    //getters中存放的就是全局共享的数据
  getters
})

export default store

3.将store对象挂载到vue实例中 (main.js)

new Vue({
  el: '#app',
  router,
    //将创建的共享数据对象,挂载到Vue实例中
    //所有的组件,就可以直接从store中换取全局的数据了
  store,
  render: h => h(App)
})

二、核心笔记

1.State

State 提供唯一的公共数据源,所有共享的数据都要统一放到Store 的 State 中进行存储。

// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
state: { count: 0 }
})

组件访问State中数据

第一种方式:

this.$store.state.全局数据名称

第二种方式:

// 1. 从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'
// 2. 将全局数据,映射为当前组件的计算属性
computed: {
 ...mapState(['count'])
}
//然后在页面直接使用就ok
2.Mutations

Mutation 用于变更 Store中 的数据。

① 只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。

② 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

 // 定义Mutation
 const store = new Vuex.Store({
     state: {
     	count: 0
     },
     mutations: {
         addN(state, step) {
         // 变更状态
         state.count += step
         }
     }
 })

组件中访问数据:

第一种方式:

// 触发mutation
methods: {
    handle2() {
        // 在调用 commit 函数,
        // 触发 mutations 时携带参数
        this.$store.commit('addN', 3)
    }
}

第二种方式:

// 1. 从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from 'vuex'

// 2. 将指定的 mutations 函数,映射为当前组件的 methods 函数
methods: {
 ...mapMutations(['add', 'addN'])
}
3.Actions

Action 用于处理异步任务。

如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发Mutation 的方式间接变更数据。

// 定义 Action
const store = new Vuex.Store({
    // ...省略其他代码
    mutations: {
        add(state) {
        state.count++
        }
    },
    actions: {
        addAsync(context) {
            setTimeout(() => {
            context.commit('add')
            }, 1000)
        } 
    }
})

组件中访问数据:

第一种方式:

// 触发 Action
methods: {
    handle() {
        // 触发 actions 的第一种方式
        this.$store.dispatch('addAsync')
    }
}

第二种方式:

// 1. 从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'

// 2. 将指定的 actions 函数,映射为当前组件的 methods 函数
methods: {
 ...mapActions(['addASync', 'addNASync'])
}
4.Getters

Getter 用于对 Store 中的数据进行加工处理形成新的数据。

① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。

② Store 中数据发生变化,Getter 的数据也会跟着变化。

// 定义 Getter
const store = new Vuex.Store({
    state: {
    	count: 0
    },
    getters: {
        showNum: state => {
        	return '当前最新的数量是【'+ state.count +'】'
        }
    }
})

组件中访问数据:

第一种方式:

this.$store.getters.名称

第二种方式:

import { mapGetters } from 'vuex'

computed: {
 ...mapGetters(['showNum'])
}
5.Modules

将store分割模块。每个模块都有自己的state、mutation、action、getter。为了更好区分每个模块的相同属性变量。
在这里插入图片描述

使用:

在store/index.js创建modules对象

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  modules,
  getters
})

组件中调用:

...mapState({
      sidebar: state => state.app.sidebar,
      device: state => state.app.device,
      showSettings: state => state.settings.showSettings,
      needTagsView: state => state.settings.tagsView,
      fixedHeader: state => state.settings.fixedHeader
    }),
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值