Vuex
- 安装 vuex 依赖包
npm install vuex --save
-
导入 vuex 包
import Vuex from 'vuex' Vue.use(Vuex)
-
创建 store 对象
const store = new Vuex.Store({ // state 中存放的就是全局共享的数据 state:{count:0} })
-
讲 store 对象挂载到 vue 实例中
new Vue({ el:'#app', render:h =>h(app), router, // 将创建的共享数据对象,挂载到 vue 实例中 // 所有的组件,就可以直接从 store 中获取全局的数据了 store })
使用
-
组件访问 state 种数据的第一种方式
this.$store.state.全局数据名称
-
第二种
<template> <div>{{count}}</div> </template> // 1. 从 vuex 种按需导入 mpState 函数 import {mapState} from 'vuex' // 通过导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性 computed:{ ...mpState(['count']) }
Mutation
-
Mutation 用于变更Store中的数据
-
只能通过 mutation 变更Store 数据,不可以直接操作 Store 中的数据
-
通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
// 定义 Mutation const store = new Vuex.Store({ state:{ count:0 }, mutations:{ add(state){ // 变更状态 state.count++ } } }) // 触发mutation methods:{ handle(){ // 触发的第一种方式 // commit 的作用就是调用某个 mutation 函数 this.$store.commit('add') } }
-
触发的第二种方式
import {mapMutation} from 'vuex' methods:{ ...mapMutation(['add']), clickButton(){ this.add() // 调用 } }
- mutation 代码书写方法二
-
Action
-
Actioin 处理异步任务
-
如果通过异步操作变更数据,必须通过 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(){ // 触发的第一种方式 this.$store.dispatch('addAsync') } }
-
第二种方式
import {mapAction} from 'vuex' methods:{ ...mapActions(['addAsync']) }
-
Getter
-
用于对 Store 中的数据进行加工处理形成的新数据
-
Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性
-
Store 中的数据变化,Getter 的数据也会跟着变化
// 定义 Getter const store = new Vuex.store({ state:{ count:0 }, getters:{ showNum:state=>{ return '当前最新的数量是【'+state.count+'】' } } })
-