store下的index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
sum: 0
}
// actions: 用于响应组件中的动作
const actions = {
jia (context, value) {
context.commit('JIA', value)
},
jian (context, value) {
context.commit('JIAN', value)
}
}
// mutations: 用于操作数据(state)
const mutations = {
JIA (state, value) {
state.sum += value
},
JIAN (state, value) {
state.sum -= value
}
}
// getters: 用于将state中的数据加工
const getters = {
bigSum(state) {
return state.sum * 10
}
}
export default new Vuex.Store({
state,
actions,
mutations,
getters
})
组件用例:
<template>
<div class="hello">
<h5>{{sum}}</h5>
<h5>{{bigSum}}</h5>
<div>{{he}}</div>
<button @click="jia(1)">+</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
name: '',
data() {
return{
}
},
methods: {
...mapActions(['jia']),
...mapMutations(['JIAN'])
},
computed: {
// sum () {
// return this.$store.state.sum
// },
// bigSum () {
// return this.$store.getters.bigSum
// },
...mapState({he: 'sum'}), // 对象写法
...mapState(['sum']), // 数组写法
...mapGetters(['bigSum'])
},
}
</script>