Vuex是什么
Vuex是一个针对Vue.js开辟的状况治理模式。说简朴点儿就是一个东西,能够治理(修正或设置)一切组件用到的数据,而不须要借助之前的event bus或许props在组件间传值。
Vuex运用场景
大型单页应用程序,存在多组件同享数据的时刻,须要用到
Vuex 核心内容
store
(一个容器对象,存储Vuex中的state,mutations,actions,getters等)
state (一个保留数据的对象,对象中的数据能够供一切组件运用)
// 1. 定义
const state = {
count: 0
}// 2. 猎取state中的值
this.$store.state.count// mapState 辅佐函数猎取多个state的值
import { mapState } from ‘vuex’
computed: mapState({// 箭头函数可以使代码更精练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count',
})
computed: mapState([
// 映照 this.count 为 store.state.count
‘count’
])// 3. 与组件的盘算属性夹杂运用
computed: {
localComputed () { / … / },
// 运用对象睁开运算符将此对象混入到外部对象中
…mapState({// ...
})
}
mutations
(一个对象,保留的是变动state的函数,也只要它能变动state中的值,触发体式格局this.$store.commit(‘函数名’,参数))
// 1. 定义
const mutations = {
increment (state) {
state.count++
}
}
// 2. 触发
this.$store.commit('increment')
// 3. 通报参数,一般参数应该是一个对象
mutations: {
increment (state, n) {
state.count += n
}
}
this.$store.commit('increment', 10)
// 4. 在组件的要领中运用
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映照为 `this.$store.commit('increment')`
// `mapMutations` 也支撑载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映照为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映照为 `this.$store.commit('increment')`
})
}
actions
(一个对象,保留的是触发mutations的函数,让mutations去修正state中的值)
// 1. 定义
const actions = {
increment: ({ commit }) => commit('increment')
}
// 2. 触发
this.$store.dispatch('increment')
// 3. 参数支撑
this.$store.dispatch('incrementAsync', {
amount: 10
})
// 4. 组件的要领中运用
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映照为 `this.$store.dispatch('increment')`
// `mapActions` 也支撑载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映照为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映照为 `this.$store.dispatch('increment')`
})
}
getters
(一个对象,保留的是一些相似与盘算属性的函数,能够经由过程他们获得任何依赖于state的新的数据)
// 1. 定义
const getters = {
evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
}
// 2. 运用
this.$store.getters.evenOrOdd
// 3. 运用其他getters作为参数
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
// 4. 组件内运用
export default {
// ...
computed: {
// 运用对象睁开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
运用vuex
npm install vuex -S
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {}
const mutations = {}
const actions = {}
const getters = {}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
// app.js
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(Counter)
})