1.Vuex简介
vuex是专门用来管理vue.js应用程序中状态的一个插件。他的作用是将应用中的所有状态都放在一起,集中式来管理。需要声明的是,这里所说的状态指的是vue组件中data里面的属性。了解vue的同学应该是明白data是怎么回事的吧,如果不懂的话,建议先学完vue的基础知识再看vuex。
Vuex有五个核心属性,state, getters, mutations, actions, modules。
2.使用步骤
这里使用的是vue3.0版本vue-cli直接创建
(1)store-index.js创建vuex
import { createStore } from 'vuex'
//创建存储
export default createStore({
//公共数据源
state: {
count: 10,
num: 100
},
//mutations变更store中的数据
mutations: {
//传入数据源
add(state) {
state.count++
},
//携带参数写法
addN(state, step) {
state.num += step
}
},
/*Action用于处理异步任务
但是在Action中还是要通过触发Mutations的方式间接变更数据*/
actions: {
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000)
}
// 携带参数写法
addAsync(context, step) {
setTimeout(() => {
context.commit('addN', step)
}, 1000)
}
},
/*
getter用于对Store的数据进行加工处理形成新的数据。
getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
Store中数据发生变化,getter的数据也会跟着变化。
*/
getters: {
showNum: state => {
return '当前最新的数量是【' + state.count + '】'
}
},
modules: {}
})
(2)main.js挂载全局
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
//引入vuex文件
import store from './store'
//全局样式
import './assets/css/common.css'
//vuex文件挂载到vue上全局使用
createApp(App).use(store).use(router).mount('#app')
(3)组件中使用state
数据源
- 方式1,直接使用插值表达式
<div class="bottom-group justify-end">
<span class="text_12" @click="add">
¥{{ $store.state.count }}</span>
<span class="text_14">起/工位/月</span>
</div>
- 方式2,计算属性
推荐
//导入vuex的辅助函数
import { mapState, mapMutations } from "vuex";
export default {
computed: {
...mapState(["num"]),
},
};
<div class="top-group flex-col">
<span class="text_8">维新软件科学园</span>
<span class="text_10">深圳市南山区中心路{{ num }}号</span>
</div>
(4)组件中使用mutations
- 方式1,关键字
commit
调用函数
change() {
/*触发vuex中mutations,commit就是调用mutatins某个函数
携带参数写法
this.$store.commit('addN',5)
*/
this.$store.commit('add')
}
- 方式2,
mapMutations
辅助函数
import { mapState, mapMutations } from "vuex";
methods: {
...mapMutations(["add","addN"]),
change() {
/* 使用引入的mapMutations中的函数
带参数使用
this.addN(5);
*/
this.add()
},
},
(4)组件中使用actions
- 方式1,关键字
dispatch
调用函数
change() {
/*触发vuex中actions,dispatch就是调用actions某个函数
this.$store.dispatch('addAsync')
*/
this.$store.dispatch('addAsync',5)
}
- 方式2,
mapActions
辅助函数
//引入mapActions
import { mapActions } from "vuex";
methods: {
...mapActions(["addAsync"]),
change() {
this.addAsync(2)
},
(5)组件中使用getter
getter用于对Store中的数据进行加工处理形成新的数据。
- 方式1,关键字
getters
使用
//插值表达式为
<p>{{$store.getters.showNum}}</p>
//js
console.log(this.$store.getters.showNum);
- 方式2,
mapGetters
辅助函数
<p>{{showNum}}</p>
import { mapGetters } from "vuex";
export default {
computed: {
...mapGetters(['showNum']),
},
};