一:Vuex的核心概念:
1.state:应用程序中需要管理的状态数据。
2.mutations:用于修改状态的方法,但必须是同步函数。
3.actions:用于提交 mutation,而不是直接变更状态,可以包含任意异步操作。
4.getters:允许组件从 sstore 中获取数据,类似于组件的计算属性。
5.modules:允许将 store 分割成模块,每个模块拥有自己的 state、mutations、actions、getters。
在App.vue中,写
<template>
<div>
<div>
APP根组件{{ $store.state.count }}
</div>
<div>
<!-- {{ name }} -->
{{ fullName }} <!-- {{ this.$store.getters.fullName }} -->
</div>
<button @click="add">按我递增10</button>
<button @click="addCount(20)">按我递增20</button>
</div>
</template>
<script>
import { mapState,mapMutations,mapActions, mapGetters } from 'vuex'
export default {
mounted() {
},
computed: {
...mapState(['count', 'name']),
...mapGetters(['fullName'])
},
methods:{
add(){
// this.addCount(10) // this.$store.commit('addCount',10)
this.addCountAsync(10) // this.$store.dispatch('addCountAsync',10)
},
...mapMutations(['addCount']),
...mapActions(['addCountAsync'])
}
}
</script>
在main.js中,写
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
在store文件夹的index.js文件,其中写
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// store理解为公共的状态空间
const store = new Vuex.Store({
// 存放初始状态
state: {
count:0,
name:'佩奇'
},
// 存放计算属性
getters: {
fullName(state){
return "小猪" + state.name
}
},
// 同步
mutations: {
addCount(state,payload){
state.count += payload
}
},
// 异步
actions: {
addCountAsync(ctx,payload){
setTimeout(()=>{
ctx.commit('addCount',payload)
},3000)
}
},
modules: {
}
})
export default store
二、 modules的使用示例:
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import moduleA from './moduleA';
import moduleB from './moduleB';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
moduleA,
moduleB
}
});
export default store;
// store/moduleA.js
const moduleA = {
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
incrementAsync(context) {
setTimeout(() => {
context.commit('increment');
}, 1000);
}
},
getters: {
doubleCount(state) {
return state.count * 2;
}
}
};
export default moduleA;
PS:1.pnpm i vuex;2.展开运算符:应用场景有展开数组元素、展开对象属性、 与解构并用等
本文介绍了Vuex在Vue应用中的关键概念,包括state、mutations、actions、getters以及如何在App.vue中管理和操作状态,以及如何使用modules进行模块化管理。
3103

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



