actions
异步修改状态信息,比如Ajax
import Vue from 'vue'
// 导入vuex
import Vuex from 'vuex'
import {INCR} from "./type";
// 通过vue安装vuex
Vue.use(Vuex)
/**
* 创建store
* @type {Store<{counter: number}>}
*/
const store = new Vuex.Store({
// 用于定义属性
state:{
counter:1000
},
// 定义用于修改属性的函数 同步提交
mutations:{
[INCR](state){
state.counter+=100;
},
// 第一个参数是 state
modifyCounter(state){
state.counter--;
},
// 传递参数
modifyCounterVal(state,val){
state.counter += val;
}
},
// 计算属性也就是getters 用于获取
getters:{
// 获取平方
getCountPF(state) {
return state.counter * state.counter;
},
// 获取 平方的2分之一
getCountTwoOne(state, getters) {
return getters.getCountPF / 2;
},
// 获取 平方的n分之一 参数传递
getCountN(state,getters){
return function (n){
return getters.getCountPF / n;
}
}
},
// 用于处理异步状态修改
actions:{
updateInfo(context,playod){
// console.log(playod)
// // 模拟网络请求
// setTimeout(() => {
// // 传参
// console.log(playod.message);
// // action 调用 mutations 修改
// context.commit(INCR);
// // 回调
// playod.success();
// },1000)
/**
* 返回 Promise,让外面可以通过then捕获返回结果
*/
return new Promise((resolve,reject) => {
// 模拟网络请求
setTimeout(() => {
// 传参
console.log(playod.message);
// action 调用 mutations 修改
context.commit(INCR);
// 回调
resolve("ajax return data!")
},1000)
})
}
}
})
export default store
app.vue
<template>
<div id="app">
<h2>访问store</h2>
<h3>{{ $store.state.counter }}</h3>
<!-- 通过commit传入方法调用-->
<button @click="$store.commit('modifyCounter')">通过mutation修改状态</button>
<!-- 传递参数-->
<button @click="$store.commit('modifyCounterVal',5)">传递参数</button>
<!-- 常量方法-->
<button @click="incr">常量方法</button>
<!-- 网络请求修改-->
<button @click="ajaxCommit">网络请求修改</button>
<button @click="ajaxCommitParam">网络请求修改(传递参数)</button>
<h2>获取Counter的平方</h2>
<h2>{{ $store.getters.getCountPF }}</h2>
<h2>获取Counter的平方 2/1</h2>
<h2>{{ $store.getters.getCountTwoOne }}</h2>
<h2>获取Counter的平方 n/1</h2>
<h2>{{ $store.getters.getCountN(5) }}</h2>
</div>
</template>
<script>
import TabBar from "./components/tabbar/TabBar";
import {INCR} from "./sotre/type";
export default {
name: 'App',
components: {
TabBar
},
methods: {
incr() {
this.$store.commit(INCR);
},
ajaxCommit() {
// 调用网络请求修改状态
this.$store.dispatch("updateInfo");
},
ajaxCommitParam() {
// 调用网络请求修改状态
// this.$store.dispatch("updateInfo", {
// message:'我是参数',
// success(){
// console.log("回调参数打印")
// }
// });
this.$store.dispatch("updateInfo", {
message:'我是参数'
}).then(res => {
console.log(res)
});
}
}
}
</script>
<style>
@import "./assets/css/base.css";
</style>

作者:彼岸舞
时间:2021\06\28
内容关于:VUE
本文属于作者原创,未经允许,禁止转发
本文介绍如何使用Vuex进行状态管理,包括状态(state)、提交(commit)、计算属性(getters)及异步操作(actions)的具体实现。通过实例展示了Vuex在Vue项目中的应用。
2万+

被折叠的 条评论
为什么被折叠?



