Vuex

安装依赖包

npm install vuex --save

导入vuex包

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

创建store对象

const store = new Vuex.Store({
  // state中从存放的就是全局共享的数据
  state: { count: 0 }
})

将store对象挂载到vue实例中

new Vue({
  el: '#app',
  render: h => h(app),
  router,
  // 将创建的共享数据对象,挂载到Vue实例中
  // 所有的组件,就可以从store中获取全局的数据了
  store
})

核心概念

State

State提供唯一的公共数据源,所有共享的数据都要同意放到Store的State中进行存储

// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
  state: { count: 0 }
})

Mutation

Mutation用于变更Store中的数据

  1. 只能通过mutation变更Store数据,不可直接操作Store中的数据
  2. 通过这种方式虽然操作起来繁琐,但可以集中监控所有数据变化

Action

Action用于处理异步任务
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但在Action中还是要触发Mutation的方式进行变更数据

Getter

Getter用于对Store中的数据进行加工处理形成新的数据

  1. Getter可以对Store中已有的数据交给你处理之后形成新的数据,类似Vue的计算属性
  2. Store中数据发生变化,Getter的数据也会跟着变化

store.js文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: { // 存放数据
count: 0
},
getters: {
showNum: state => {
return '当前最新的数量是【' + state.count + '】'
}
},
mutations: { // 状态变更
add(state) {
state.count++
},
addN(state, step) { // step为其他参数
state.count += step
}
},
actions: { // 异步处理
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000)
},
addNAsync(context, step) { // step为其他参数
setTimeout(() => {
context.commit('addN', step)
}, 1000)
}
}
})

// 访问数据

// 1
this.$store.state.全局变量名称
// 2
import { mapState } from 'vuex'

export default {
compoute: {
...mapState(['count']) // 将全局属性映射为计算属性
}
}

{{ count }} // template中引用

// 变更数据

// 1
export default {
methods: {
handle() {
this.$store.commit('add')
},
hanle2() {
this.$store.commit('addN', 3)
}
}
}
// 2
import { mapMutations } from 'vuex'

export default {
methods: {
...mapMutations(['add', 'addN'])
}
}

this.add() this.addN(3) // 调用

// 异步处理数据

// 1
export default {
methods: {
handle1() {
this.$store.dispatch('addAsync')
},
handle2() {
this.$store.dispatch('addNAsync', 5)
}
}
}
// 2
import { mapActions } from 'vuex'

export default {
methods: {
...mapActions(['addAsync', 'addNAsync'])
}
}

this.addAsync() this.addNAsync(5) // 调用

// 使用Getter
// 1
this.$store.getters.名称

// 2
import { mapGetters } from 'vuex'

export default {
computed: {
...mapGetters(['showNum'])
}
}

原文地址:https://www.cnblogs.com/miao91/p/15708611.html