Vue项目中使用Vuex
Vuex的安装及导入
npm安装
npm install vuex --save
store.js中全局引入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
getters: {
}
})
注:创建vue项目时勾选vuex会默认生成store.js
Vuex的state用法
state的第一种用法(this.$store.state.变量名)
export default new Vuex.Store({
state: {
count: 0
}
})
定义了全局变量count,在组件中使用:<p>{{this.$store.state.count}}</p>
state的第二种用法(mapState)
1、在使用全局数据的组件中,从vuex中导入mapState函数
import { mapState } from 'vuex'
2、通过导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed属性,使用方法:<p>{{count}}</p>
export default {
// 第一种
computed: mapState({
count: state => state.count,
})
// 第二种,扩展语法
computed: {
...mapState(['count'])
}
}
注:上述两种state的调用方式都可以使用,根据自己的喜好
Vuex的mutations用法
mutations的作用
1、mutations用于变更store中的数据(不推荐直接修改state中的数据,因为不能监测到是哪个组件改变的全局数据)
2、mutations可以集中的监测state中数据的变化
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state){ //第一个参数就是上面定义的state
state.count++
}
}
})
mutations的第一种调用方式
this.$store.commit('定义的mutations')
<p>{{count}}</p>
<button @click="btnAdd">增加</button>
btnAdd(){
this.$store.commit('add') //全局改变count
}
mutations的参数传递
1、定义mutations
state: {
count: 0
},
mutations: {
addN(state, step){ // 第一个参数是上面定义的state,第二个参数是调用时传递的
state.count+=step
}
},
2、调用mutations
btnAdd(){
this.$store.commit('addN',3) // 每次加三的操作
}
mutations的第二种调用方式(mapMutations)
1、在使用全局数据的组件中,从vuex中导入mapMutations函数
import { mapMutations } from 'vuex'
2、通过导入的mapMutations函数,将当前组件需要的mutations,映射为当前组件的methods方法
methods:{
...mapMutations(['add','addN']),
btnAdd(){
this.add()
},
btnAddN(){
this.addN(3)
}
}
注:上述两种mutations的调用方式都可以使用,根据自己的喜好
mutations的函数中不能有异步的操作
需要异步的操作请使用actions
Vuex的actions用法
actions的作用及定义
1、actions专门用于处理异步操作(延时操作,调用接口等等)
2、操作的步骤是在actions中触发mutations,切记不能在actions中直接修改state中的值,而是通过context.commit()去触发某个mutations
state: {
count: 0
},
mutations: {
addN(state, step){ // 第一个参数是上面定义的state,第二个参数是调用时传递的
state.count+=step
}
},
actions: {
addAsync(context,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
},
actions的第一种调用方式
this.$store.dispatch('定义的actions') // 如果携带参数附在后面
btnAdd(){
this.$store.dispatch('addAsync',3)
}
actions的第二种调用方式
1、在使用全局数据的组件中,从vuex中导入mapActions 函数
import { mapActions } from 'vuex'
2、通过导入的mapActions 函数,将当前组件需要的actions,映射为当前组件的methods方法
...mapActions(['addAsync']),
btnAdd(){
this.addAsync(3)
}
Vuex的getters用法
getters的作用及定义
1、getters可以对state中已有的数据进行加工处理成新的数据
2、state中的数据发生变化,getters中也随着变化
3、getters不会改变state中的数据
state: {
count: 0
},
getters: {
showCount(state){
return '当前最新的数量是['+state.count+']'
}
}
getters的第一种使用方法
this.$store.getters.名称
getters的第二种使用方法
1、在使用全局数据的组件中,从vuex中导入mapGetters 函数
import { mapGetters } from 'vuex'
2、通过导入的mapGetters 函数,将当前组件需要的getters,映射为当前组件的computed属性
computed:{
...mapGetters(['showCount'])
},