vuex 的基本使用

2023-05-30 0 1,109

vue 的基本上采用

加装 vuex 倚赖包
cnpm install –save vuex
引入 vuex 包
import Vuex from “vuex” Vue.use(Vuex)
建立 store 对象
const store = new Vuex.Store({ // state 中放置的是自上而下共享资源的统计数据 state: {count: 0} })

在工程项目子目录建立两个 .prettierrc 文档

载入
{ “semi”: false, // 不采用王劝 “singleQuote”: true // 将单引号转化成下划线 }

vuex 核心理念基本概念

State

单个状况树(在 vue 模块中赢得 vuex 的状况)
data(){ return{ num: this.$store.state.count, } }

Mutation

用来变更 Store 中的统计数据只能通过 mutation 变更 Store 统计数据,不可以直接操作 Store 中的统计数据通过这种方式虽然操作起来有些繁琐,但是可以集中监控所有统计数据的变化
<!– store.js –> state: { count: 0, }, mutations: { add(state,step){ state.count += step }, sub(state,step){ state.count -= step; }, }, <!– Add.vue –> methods:{ add(){ this.$store.commit(“add”,1) }, add5(){ this.$store.commit(“add”,5) }, }

commit 作用,是调用某个 mutations 函数this.$store.commit() 是触发 mutations 的第一种方式,触发 mutations 的第二种方式:

从 vuex 中按需引入 mapMutations 函数

import { mapMutations } from “vuex”

通过刚才引入的 mapMutations 函数,将需要的 mutations 函数,映射为当前模块的 methods 方法:
methods:{ …mapMutations([“add”,”addN”]), add(){ this.add() }, addN(){ this.addN(5) } }

不要再 mutations 中执行 异步操作 Action 用来处理异步操作Action

用于处理异步任务如果通过异步操作变更统计数据,必须通过 Action ,而不能采用 Mutations , 但是在 Action 中还是要通过触发 Mutations 的方式变更统计数据
<!– 定义 Action –> const store = new Vuex.Store({ mutations: { add(state,step){ state.count += step } }, actions:{ addAsync(context){ setTimeout(() => { context.commit(“add”) },1000) } } }) 触发 Action methods:{ addAsync(){ this.$store.dispatch(“addAsync”,1) } }
通过刚才引入的 mapActions 函数,将需要的 actions 函数,映射为当前组建的 methods 方法:
<!– 将指定的 actions 函数,映射为当前模块的 methods 函数 –> methods:{ …mapActions([“addAsync”,”addNAsync”]) }

Getter

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

Getter 可以对 Store 中已有统计数据加工处理之后形成新的统计数据,类似 Vue 的计算属性Store 中统计数据发生变化v,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”]) } <h1>{{showNum}}</h1>

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务