vue2备忘之vuex
准备
- 配置——vue2需要vuex3
import Vue from "vue";
import Vuex, { Store } from "vuex"
import comA from "./comA.js"
Vue.use(Vuex)
const store = new Store({
})
export default store
- 挂载到main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
}).$mount('#app')
- 分模块后state、mutations、actions、getters的使用
const comA = {
namespaced: true,
state: () => {
return {
a: 1,
b: 2,
}
},
mutations: {
add(state, value) {
state.a += value
state.b += value
},
dis(state, value) {
state.a -= value
state.b -= value
},
},
actions: {
exDis(ctx, value) {
ctx.commit('dis', value)
}
},
getters: {
sum: (state) => {
return state.a + state.b
}
},
}
export default comA
- 将模块挂载index上
import Vue from "vue";
import Vuex, { Store } from "vuex"
import comA from "./comA.js"
Vue.use(Vuex)
const store = new Store({
modules: {
comA
}
})
export default store
使用
- state使用
$store.state.模块名.变量名
mapState(‘模块名’, [‘变量名’])
- getters使用
$store.getters[“模块名/变量名”]
mapGetters(‘模块名’,[‘变量名’])
- mutations使用
$store.commit(‘模块名/变量名’,传入的变量)
mapMutations(‘模块名’, [‘变量名’])
- actions使用
$store.dispatch(‘模块名/变量名’,传入的变量)
mapActions(‘模块名’,[‘变量名’])
<template>
<div>
routerA
<button @click="toB">toB</button>
<h1>vuex</h1>
<p>
{{ $store.state.comA.a }} + {{ $store.state.comA.b }} = {{ $store.getters["comA/sum"] }}
<button @click="$store.commit(`comA/add`,5)">+</button>
<button @click="$store.dispatch(`comA/exDis`,5)">-</button>
</p>
<p>
{{ a}}+{{ b }}={{ sum }}
<button @click="add(5)">+</button>
<button @click="exDis(5)">-</button>
</p>
</div>
</template>
<script>
import { mapActions,mapGetters,mapMutations,mapState } from 'vuex'
export default {
name: 'comA',
components: {
},
mixins: [],
props: {
},
data() {
return {
}
},
computed: {
...mapState('comA', ['a', 'b']),
...mapGetters('comA',['sum'])
},
watch: {
},
mounted() {
},
methods: {
toB() {
this.$router.push('/comB?name=这是B界面')
},
...mapMutations('comA', ['add']),
...mapActions('comA',['exDis'])
}
};
</script>
<style lang='' scoped>
</style>