Vuex实现了数据的共享
当有数据需要在多个组件中被使用的时候,就可以使用Vuex
搭建Vuex开发环境
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
render: (h) => h(App),
store,
}).$mount('#app')
store/index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const state = {
sum: 0
};
const mutations = {
increment(state, value) {
state.sum += value
},
decrement(state, value) {
state.sum -= value
},
incrementOdd(state, value) {
if (value % 2 !== 0) {
state.sum += value
}
},
};
const actions = {
increment(context, value) {
context.commit("increment", value);
},
};
export default new Vuex.Store({
state,
mutations,
actions,
});
Count.vue
<script>
export default {
name: 'Count',
data() {
return {
n: 1
}
},
methods: {
increment() {
this.$store.dispatch('increment', this.n)
},
decrement() {
this.$store.commit('decrement', this.n)
},
incrementOdd() {
this.$store.commit('incrementOdd', this.n)
},
incrementWait() {
setTimeout(() => {
this.$store.dispatch('increment', this.n)
}, 1000)
}
},
computed: {
sum() {
return this.$store.state.sum
}
}
}
</script>
<template>
<div>
<h1>当前和为:{{ sum }}</h1>
<select v-model="n">
<option v-for="item in 3" :key="item" :value="item">
+ {{ item }}
</option>
</select>
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
<button @click="incrementOdd">奇数加</button>
<button @click="incrementWait">延迟加</button>
</div>
</template>
<style scoped>
* {
margin: 5px;
padding: 0;
}
</style>
任何组件上,都可以通过 this.$store.dispatch 操作store中的action方法
通过this.$store.commit操作store中的mutation方法