咱们都知道组件之间的传值,有父组件传子组件、子组件传父组件、兄弟组件之间传值。可是若是个组件均不是以上状况的两个组件怎么传值呢,这就须要咱们学习的 vuex 来解决。vue
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。简单点说,就是一个工具,能够管理(修改或者设置)全部组件用到的数据,并且不须要借助以前的event bus 或者 props 在组件之间传值。vuex
2.vuex 的核心npm
store(一个容器对象,储存vuex 中的 state mutations actions getters)app
1 // 1. 定义 2 const state = { 3 count: 0 4 } 5 6 // 2. 获取state中的值 7 this.$store.state.count 8 9 // mapState 辅助函数获取多个state的值 10 import { mapState } from 'vuex' 11 computed: mapState({ 12 // 箭头函数可以使代码更简练 13 count: state => state.count, 14 // 传字符串参数 'count' 等同于 `state => state.count` 15 countAlias: 'count', 16 }) 17 computed: mapState([ 18 // 映射 this.count 为 store.state.count 19 'count' 20 ]) 21 22 // 3. 与组件的计算属性混合使用 23 computed: { 24 localComputed () { /* ... */ }, 25 // 使用对象展开运算符将此对象混入到外部对象中 26 ...mapState({ 27 // ... 28 }) 29 }
1 // 1. 定义 2 const mutations = { 3 increment (state) { 4 state.count++ 5 } 6 } 7 8 // 2. 触发 9 this.$store.commit('increment') 10 11 // 3. 传递参数,一般参数应该是一个对象 12 mutations: { 13 increment (state, n) { 14 state.count += n 15 } 16 } 17 this.$store.commit('increment', 10) 18 19 // 4. 在组件的方法中使用 20 methods: { 21 ...mapMutations([ 22 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')` 23 24 // `mapMutations` 也支持载荷: 25 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)` 26 ]), 27 ...mapMutations({ 28 add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')` 29 }) 30 }
1 // 1. 定义 2 const actions = { 3 increment: ({ commit }) => commit('increment') 4 } 5 6 // 2. 触发 7 this.$store.dispatch('increment') 8 9 // 3. 参数支持 10 this.$store.dispatch('incrementAsync', { 11 amount: 10 12 }) 13 14 // 4. 组件的方法中使用 15 methods: { 16 ...mapActions([ 17 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` 18 19 // `mapActions` 也支持载荷: 20 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)` 21 ]), 22 ...mapActions({ 23 add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` 24 }) 25 }
1 // 1. 定义 2 const getters = { 3 evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd' 4 } 5 6 // 2. 使用 7 this.$store.getters.evenOrOdd 8 9 // 3. 使用其余getters做为参数 10 getters: { 11 // ... 12 doneTodosCount: (state, getters) => { 13 return getters.doneTodos.length 14 } 15 } 16 17 // 4. 组件内使用 18 export default { 19 // ... 20 computed: { 21 // 使用对象展开运算符将 getter 混入 computed 对象中 22 ...mapGetters([ 23 'doneTodosCount', 24 'anotherGetter', 25 // ... 26 ]) 27 } 28 }
3.1 安装 vuex: npm install vuex -S函数
3.2 使用方法:工具
1 // store.js 2 import Vue from 'vue' 3 import Vuex from 'vuex' 4 5 Vue.use(Vuex) 6 const state = {} 7 const mutations = {} 8 const actions = {} 9 const getters = {} 10 export default new Vuex.Store({ 11 state, 12 getters, 13 actions, 14 mutations 15 }) 16 17 // app.js 18 import store from './store' 19 20 new Vue({ 21 el: '#app', 22 store, 23 render: h => h(Counter) 24 })