首先vuex概念比较多,一定要搞懂里面的概念,可以参考官网Vuex2.0概念,我写此文的目的是希望能对前端爱好者提供个参考,加深对vuex2.0各核心概念的理解。
测试组件:vuex.vue
<template>
<div>
<h1>vuex 测试</h1>
Clicked: {{ getCount }} times
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import { mapActions } from 'vuex'
export default {
computed: {
// 使用对象展开运算符将 getters 混入 computed 对象中
...mapGetters([
'getCount'
// ...
])
},
methods: {
...mapActions([
'increment', // 映射 this.increment() 为 this.$store.dispatch('increment')
'decrement'
])
//...mapActions({
// add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')
//})
}
}
</script>
actions.js文件:
//test
export const increment = ({commit}) => {
commit('INCREMENT')
}
export const decrement = ({commit}) => {
commit('DECREMENT')
}
getters.js文件:
//test
export const getCount = state => {
return state.count
}
store.js文件:
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
Vue.use(Vuex)
// 应用初始状态
const state = {
count: 10
}
// 定义所需的 mutations
const mutations = {
INCREMENT(state) {
state.count++
},
DECREMENT(state) {
state.count--
}
}
// 创建 store 实例
export default new Vuex.Store({
actions,
getters,
state,
mutations
})
切记:
要先在main.js 引入
import store from './vuex/store'
import Vuex from 'vuex'
new Vue({
//el: '#app',
//template: '<App/>',
router,
store,
//components: { App }
render: h => h(App)
}).$mount('#app')