最近因为另外一个前端年后要休婚假(羡慕嫉妒有那么长的假期!!),so,他负责的项目就由我来接手,其中就有一个还未完成的管理后台项目,基于 vue + element UI + vuex 实现的。由于自己也蛮久没有用到vuex了,此文就用来一起回忆复习吧。你觉得有用,就不要吝啬你的点赞哟~这就是对我更文的极大动力。
何为vuex?
附上一张官网的图片
我想,有些人看这图片一脸懵了,不急,往下看。
Vuex有五大核心概念:State、Getter、Mutation、Action、Module。(并不是每次都需要用到所有的这五个,各取所需即可)
State:存储状态数据(类似 vue 的data,但是 state 不允许直接修改,只允许定义一系列事件进行触发更改(mutation))
Getter:从状态数据派生数据(相当于State的计算属性)。
Mutation:存储用于同步更改状态数据的方法,默认传入的参数为state。
Action:存储用于异步更改状态数据,但不是直接更改,而是通过触发Mutation方法实现,默认参数为context。
Module:Vuex模块化(更改 Vuex 的 store 中的状态的唯一方法是提交mutation。)。
安装使用
1.npm/cnpm安装
cnpm install vuex --save
或者
npm install vuex --save
2.新建store/store.js文件,引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({ //store对象
state: {
age: ''
},
getters: {
getAge(state) {
return 'hello ' + state.age;
}
},
mutations: {
setAge(state, age) {
state.age= age;
}
},
actions: {
setAge(context, age) {
setTimeout(() => {
context.commit('setAge', age);
}, 1000);
}
}
});
export default store; //导出
3.在main.js中引入store
import store from './store/store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
注:每个组件都可以通过this.$store来访问全局单例对象store
<template>
<div>
<button @click="increse">+</button>
</div>
</template>
<script>
export default {
name: 'Demo',
methods: {
increse() {
this.$store.commit('increse', {
step: 10
})
}
}
}
</script>
调用store中的mutations方法只能通过提交的方式this.$store.commit(‘方法名’, 负载参数)这一种形式来调用.
注:想要访问vuex中的各个对象实例,可以通过以下两种方式
方式一:
this.$store.state.name;
this.$store.getters.getName;
this.$store.commit('mutationSetAge', 18);
this.$store.dispatch('actionSetAge', 8);
方式二:
辅助函数
1.在需要应用的子组件中引入
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
2.在计算属性computed中引入state和getters
computed: {
...mapState({ // 把 `this.age` 映射为 `this.$store.state.age`
name: state => state.name
}),
...mapGetters({ // 把 `this.getAge` 映射为 `this.$store.getters.getAge`
getAge: getAge
})
}
3.在methods中引入mutations和actions
methods: {
...mapMutations([ // 将 `this.mutationSetAge()` 映射为 `this.$store.commit('mutationSetAge')`
'mutationSetAge'
]),
...mapActions([ // 将 `this.actionSetAge()` 映射为 `this.$store.dispatch('actionSetAge')`
'actionSetAge'
])
}
注:’…'这三个点是指ES6当中的扩展运算符,用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中。
若有不足之处,请指出谢谢!会及时进行修改补充。