// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
}
}
});
// ComponentA.vue
<template>
<button @click="incrementCount">Increment</button>
</template>
<script>
export default {
methods: {
incrementCount() {
this.$store.commit('increment');
}
}
};
</script>
// ComponentB.vue
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count;
}
},
watch: {
count: {
immediate: true,
handler(newCount) {
if (newCount > 0) {
this.doSomething();
}
}
}
},
methods: {
doSomething() {
// 执行某个方法
}
}
};
</script>