vuex使用指南转载

34次阅读

共计 3749 个字符,预计需要花费 10 分钟才能阅读完成。

使用
在 Vue 的单页面应用中使用,需要使用 Vue.use(Vuex)调用插件。
使用非常简单,只需要将其注入到 Vue 根实例中。
import Vuex from ‘vuex’
Vue.use(Vuex)
const store = new Vuex.Store({
state: {

count: 0

},
getter: {

doneTodos: (state, getters) => {return state.todos.filter(todo => todo.done)
}

},
mutations: {

increment (state, payload) {state.count++}

},
actions: {
addCount(context) {

// 可以包含异步操作
// context 是一个与 store 实例具有相同方法和属性的 context 对象

}
}
})
// 注入到根实例
new Vue({
el: ‘#app’,
store,
template: ‘<App/>’,
components: {App}
})

然后改变状态:
this.$store.commit(‘increment’)

Vuex 主要有四部分:

state:包含了 store 中存储的各个状态。
getter: 类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
mutation: 一组方法,是改变 store 中状态的执行者。
action: 一组方法,其中可以含有异步操作。

state
Vuex 使用 state 来存储应用中需要共享的状态。为了能让 Vue 组件在 state 更改后也随着更改,需要基于 state 创建计算属性。
const Counter = {
template: <div>{{count}}</div>,
computed: {

count () {return this.$store.state.count  // count 为某个状态}

}
}

getters
类似于 Vue 中的 计算属性,可以在所以来的其他 state 或者 getter 改变后自动改变。
每个 getter 方法接受 state 和其他 getters 作为前两个参数。
getters: {

doneTodos: (state, getters) => {return state.todos.filter(todo => todo.done)
}

}

mutations
前面两个都是状态值本身,mutations 才是改变状态的执行者。mutations 用于同步地更改状态
// …
mutations: {
increment (state, n) {

state.count += n

}
}

其中,第一个参数是 state,后面的其他参数是发起 mutation 时传入的参数。
this.$store.commit(‘increment’, 10)

commit 方法的第一个参数是要发起的 mutation 名称,后面的参数均当做额外数据传入 mutation 定义的方法中。
规范的发起 mutation 的方式如下:
store.commit({
type: ‘increment’,
amount: 10 // 这是额外的参数
})

额外的参数会封装进一个对象,作为第二个参数传入 mutation 定义的方法中。
mutations: {
increment (state, payload) {

state.count += payload.amount

}
}

actions
想要异步地更改状态, 需要使用 action。action 并不直接改变 state,而是发起 mutation。
actions: {
incrementAsync ({commit}) {

setTimeout(() => {commit('increment')
}, 1000)

}
}

发起 action 的方法形式和发起 mutation 一样,只是换了个名字 dispatch。
// 以对象形式分发
store.dispatch({
type: ‘incrementAsync’,
amount: 10
})

action 处理异步的正确使用方式
想要使用 action 处理异步工作很简单,只需要将异步操作放到 action 中执行(如上面代码中的 setTimeout)。
要想在异步操作完成后继续进行相应的流程操作,有两种方式:

action 返回一个 promise。
而 dispatch 方法的本质也就是返回相应的 action 的执行结果。所以 dispatch 也返回一个 promise。

store.dispatch(‘actionA’).then(() => {
// …
})

利用 async/await。代码更加简洁。

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
async actionA ({commit}) {

commit('gotData', await getData())

},
async actionB ({dispatch, commit}) {

await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())

}
}

各个功能与 Vue 组件结合
将 state 和 getter 结合进组件需要使用计算属性:
computed: {

count () {
  return this.$store.state.count 
  // 或者 return this.$store.getter.count2
}

}

将 mutation 和 action 结合进组件需要在 methods 中调用 this.$store.commit()或者 this.$store.commit():
methods: {

changeDate () {this.$store.commit('change');
},
changeDateAsync () {this.$store.commit('changeAsync');
}

}

为了简便起见,Vuex 提供了四个方法用来方便的将这些功能结合进组件。

mapState
mapGetters
mapMutations
mapActions

示例代码:
import {mapState, mapGetters, mapMutations, mapActions} from ‘vuex’

// ….
computed: {
localComputed () { // },
…mapState({

// 为了能够使用 `this` 获取局部状态,必须使用常规函数
count(state) {return state.count + this.localCount}

}),
…mapGetters({

getterCount(state, getters) {return state.count + this.localCount}

})
}
methods: {
…mapMutations({

   add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
}),

…mapActions({

  add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})

}

如果结合进组件之后不想改变名字,可以直接使用数组的方式。
methods: {

...mapActions(['increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

  // `mapActions` 也支持载荷:'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),

}

将 store 分割为模块。
可以将应用的 store 分割为小模块,每个模块也都拥有所有的东西:state, getters, mutations, actions。
首先创建子模块的文件:
// initial state
const state = {
added: [],
checkoutStatus: null
}
// getters
const getters = {
checkoutStatus: state => state.checkoutStatus
}
// actions
const actions = {
checkout ({commit, state}, products) {
}
}
// mutations
const mutations = {
mutation1 (state, { id}) {
}
}
export default {
state,
getters,
actions,
mutations
}

然后在总模块中引入:
import Vuex from ‘vuex’
import products from ‘./modules/products’ // 引入子模块

Vue.use(Vuex)
export default new Vuex.Store({
modules: {

products   // 添加进模块中

}
})

其实还存在命名空间的概念,大型应用会使用。需要时查看文档即可。Vuex 的基本使用大致如此。

作者:胡不归 vac
链接:https://www.jianshu.com/p/aae…
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

正文完
 0