vue2-vuex的使用

106 阅读1分钟

一、vuex的简介

vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享

二、使用vuex的好处

  • 能够在vuex中集中管理共享的数据,易于开发与维护
  • 能够高效地实现组件之间的数据共享,提高开发效率
  • 存储在vuex中的数据是响应式的,能够保持数据与页面的同步

三、vuex安装

//npm安装
npm install vuex@next --save

//yarn安装
yarn add vuex@next --save

四、vuex的引用

  1. vue目录下,新建stroe目录,创建index.js文件
//index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const new Vuex.Store({
state:{},
mutations:{},
actions:{},
getters:{}
})
export default store
  1. 在main.js如何文件引入index.js,挂载到vue实例
import store from './store'

new Vue({
store,
render:h=>h(App)
}).$mount('#app')

五、vuex的使用

  • State 提供唯一的公共数据源,共享数据统一放到state中存储
使用数据
1.
this.$store.state.count
2.
导入
import {mapState} from 'vuex'

映射
compouted:{
...mapState(['count'])
}
获取
this.count
  • Mutation 变更store中的数据,不能写异步操作
变更数据
1.
定义
mutations:{
add(state){
state.count++
}
}
触发
this.$store.commit('add')

传递参数
定义
mutations:{
addN(state,step){
state.count+=step
}
}
触发
this.$store.commit('addN',3)

2.
导入
import {mapMutations} from 'vuex'

映射
methods:{
...mapMutations(['add','addN'])
}
使用 
this.add()
  • Action 异步操作变更数据
1.
定义
actions:{
addAsync(content){
setTimeout(()=>{
content.commit('add')
},1000)
}
}

触发
this.$store.dispatch('addAsync')

2.
导入
import {mapActions} from 'vuex'

映射
methods:{
...mapActions(['subAsync'])
}

使用
this.subAsync()
  • Getter 对state数据加工处理,不改变state数据值
1.
定义
getters:{
showNum(state){
return '当前的数据是:'+state.count
}
}
this.$store.getters.showNum

2.
导入
import {mapGetters} from 'vuex'

映射
computed:{
...mapGetters(['showNum'])
}
获取
this.showNum