前言:我们的项目登录部分需要与甲方的系统保持一致,甲方给的代码用到了vuex。所以来学习一下vuex,主要参考内容有官网,以及视频。
1.简介
vuex是vue配套的公共数据管理工具,我们可以将共享的数据保存在vuex中,方便整个程序中的任何组件都可以获取和修改vuex中保存的公共数据。(以后数据就不要一层一层/借助父组件传递了)
优点:
- 1.能够在vuex中集中管理共享的数据,易于开发和维护
- 2.能够高效的实现组件之间的数据共享,提高开发效率。
- 3.存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步。
一般情况下,只有组件间共享的数据,才有必要存储在vuex中;对于组件间的私有数据,依旧存储在组件自身的data中即可。
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)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
2.state
state提供唯一的公共数据源,所有共享的数据都要统一放在store的state中进行储存。
使用state的两种方式
1.this.$store.state.全局数据名称
-
import {mapState} from 'vuex'
computed: { ...mapState([' ']) }
3.mutations
mutations用于变更store中的数据。
注意
- 只有mutations中的函数,才有权力修改store中的数据
- mutations里不能包含异步的操作
①只能通过mutations变更store数据,不可以直接操作store中的数据 ②通过这种方式操作起来虽然稍微繁琐一点,但可以集中监控所有数据的变化
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state,step){
//变更状态
state.count+=step
}
}
})
触发mutations的两种方法
-
this.$store.commit('add', 可以传参)
-
①从vuex中按需导入mapMutations函数 import {mapMutations} from 'vuex'
②通过刚才按需导入的mapMutations函数,映射为当前组建的methods函数
// store
mutations: {
add(state) {
// 变更状态
state.count++
},
sub(state) {
state.count--
},
addN(state, step) {
// 变更状态
state.count += step
},
subN(state, step) {
state.count -= step
}
},
// 组件A
import { mapState,mapMutations } from 'vuex'
methods:{
...mapMutations(['sub','subN']),
decrement(){
// 调用
this.sub()
},
decrementN(){
this.subN(5)
}
}
4.actions专门用来处理异步的任务
Actions用于处理异步任务。
如果通过异步操作变更数据,必须通过Actions,而不能直接使用Mutations,但是在Actions中还是要通过触发Mutations的方式来简介变更数据.
触发actions的两种方法
- this.$store.dispatch触发
improt {mapActions} from 'vuex'
methods:{
...mapActions(['subAsync']),
decrementAsync(){
this.subAsync()
}
}
5.getter
getter用于对store中的数据进行加工处理形成新的数据。
①getter可以对store中已有的数据进行加工处理后形成新的数据,类似vue计算属性。 ②store中的数据发生变化,getter中的数据也会随之变化。
getter不会修改store中的数据,它只起到包装的作用。
使用getter的两种方法
1.this.$store.getters.名称
-
import {mapGetters} from 'vuex'
computed: { ...mapGetters([' ',' '])
6.简写
通过mapState,mapMutations,mapActions,mapGetters映射过来的计算属性,或者方法可以直接调用,不用再commit或者dispatch
<button @click="subAsync">-1Async</button>
import {mapActions} from 'vuex'
//...省略一些代码
methods: {
...mapActions(['subAsync']),
},