State
State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储。
//store下的index.js文件
export default new Vuex.Store({
//在state内定义共享数据
state: {
count: 0
},
})
组件访问 State 中数据的第一种方式:
//在组件中this可以省略 count是自定义的共享数据
this.$store.state.count
组件访问 State 中数据的第二种方式:
//在template标签下
{{count}}
// 1. 从 vuex 中按需导入 mapState 函数
<script>
import { mapState } from 'vuex'
// 2. 将全局数据,映射为当前组件的计算属性
computed: {
...mapState(['count'])
}
</script>
Mutation
Mutation 用于变更 Store中 的数据。 不建议在组件中直接对store中的数据做更改!
- 只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。
- 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
this.$store.commit() 是触发 mutations 的第一种方式
//store/index.js文件
mutations: {
add(state) {
state.count++
},
addN(state, step) {
state.count += step
},
},
//组件
<button @click="handle1">+1</button>
<button @click="handle2">+N</button>
methods:{
handle1(){
this.$store.commit('add')
},
handle2(){
this.$store.commit('addN',3)
}
}
触发 mutations 的第二种方式:
//store/index.js文件
mutations: {
sub(state) {
state.count--
},
subN(state, step) {
state.count -= step
}
},
<button @click="handle1">-1</button>
<button @click="handle2">-N</button>
//按需导入
import {mapMutations} from 'vuex'
methods:{
...mapMutations(['sub','subN']),
handle1(){
this.sub()
},
handle2(){
this.subN(3)
}
},
Action
Action 用于处理异步任务。
如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发
Mutation 的方式间接变更数据。
this.$store.dispatch() 是触发 actions 的第一种方式;
//异步函数需要写在actions里
actions: {
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000)
},
//传参
addNAsync(context, step) {
setTimeout(() => {
context.commit('addN', step)
}, 1000)
},
}
//组件
<button @click="handle3">+1 async</button>
<button @click="handle4">+N async</button>
handle3(){
//dispatch专门用来触发action函数
this.$store.dispatch('addAsync')
},
handle4(){
//dispatch专门用来触发action函数
this.$store.dispatch('addNAsync',5)
}
触发 actions 的第二种方式:
//异步函数需要写在actions里
actions: {
subAsync(context) {
setTimeout(() => {
context.commit('sub')
}, 1000)
},
subNAsync(context, step) {
setTimeout(() => {
context.commit('subN', step)
}, 1000)
},
//组件
<button @click="subAsync">-1 async</button>
<button @click="subNAsync(4)">-N async</button>
methods:{
//导入后可以直接在html中使用
...mapActions(['subAsync','subNAsync']),
},
Getter
Getter 用于对 Store 中的数据进行加工处理形成新的数据。
① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。
② Store 中数据发生变化,Getter 的数据也会跟着变化。
// 定义 Getter
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
showNum: state => {
return '当前最新的数量是【'+ state.count +'】'
}
}
})
使用 getters 的第一种方式:
//this.$store.getters.名称
<h3>{{$store.getters.showNum}}</h3>
使用 getters 的第二种方式:
<h3>{{showNum}}</h3>
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
}
来源:oschina
链接:https://my.oschina.net/u/4139437/blog/3190415