Vuex采用和Redux类似的单向数据流的方式来管理数据。用户界面负责触发动作(Action)进而改变对应状态(State),从而反映到视图(View)上。
安装:
npm Install --save vuex
引入:
store.js
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
const mutations = {...};
const actions = {...};
const state = {...};
Vuex.Store({
state,
actions,
mutation
});
main.js
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
1、vuex的state
简单的说,vuex的使用就是兄弟组件之间共享数据或者通信。
由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:
computed() {
count:funtion() {
return this.$store.state.count
}
}
当一个组件需要获取多个状态时候, mapState 辅助函数可以帮助我们生成计算属性。
example.vue中
方式1:
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countA: 'count',
// 为了能够使用 `this` 获取局部状态(当前组件内的数据),必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
方式2:
import { mapState } from 'vuex'
export default {
// ...
computed(){
mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countA: 'count',
// 为了能够使用 `this` 获取局部状态(当前组件内的数据),必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
}
方式3:
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。如下:
import { mapState } from 'vuex'
export default {
// ...
computed(){
mapState({
‘count’
})
}
}
其实这两种写法是一样的,最开始学习使用的时候,我很迷惑,为什么有两种写法,而且会用混。
注释:本文案例都是基于vue-cli脚手架的。
2、vuex的getter
vue的getter方法用于对store中state衍生出来的状态,换句话说就是想得到state中的经过处理过的数据。
store.js
const store = new Vuex.Store({
state: {
count: 1
},
getters: {
getCount:function(state){
return ++state.count
}
}
})
组件内使用:
方式1:
computed(){
count:function(){
return this.$store.getters.getCount
}
}
方式2:
import { mapGetters } from 'vuex'
export default {
computed() {
mapGetters({
// 映射 `this.countData` 为 `store.getters.doneTodosCount`
countData: 'getCount'
})
}
}
方式3:(将 store 中的 getter 映射到局部计算属性)
import { mapGetters } from 'vuex'
export default {
computed(){
mapGetters([
'getCount'
])
}
}
3、vuex的mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation.(Vue 建议我们mutation 类型用大写常量表示)
store.js
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
INCREMENT (state,n) {
// 变更状态
state.count += n
}
}
})
组件内使用:
this.$store.commit('INCREMENT', 10)
store.commit 传入额外的参数,即 mutation 的 载荷。在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读。
store.js
mutations: {
INCREMENT (state, payload) {
state.count += payload.amount
}
}
组件内使用:
store.commit('INCREMENT ', {
amount: 10
})
mutation 必须同步执行.
4、vuex的action
Action 类似于 mutation,不同在于:
1.Action 提交的是 mutation,而不是直接变更状态。
2.Action 可以包含任意异步操作。
store.js
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
action 内部执行异步操作
学习中,待更新...........
网友评论