示例
1、main.js中添加getters
import { createApp } from 'vue';
import { createStore } from 'vuex';
import App from './App.vue';
const store = createStore({
state() {
return {
counter: 0,
};
},
mutations: {
increment(state) {
state.counter += 10;
},
incrementBy(state, payload) {
state.counter += payload.value;
},
},
getters: {
finalCounter(state) {
return state.counter * 3;
},
//normalizedCounter(_, getters) { //if state is not needed, it can be replaced with _ to use second argument for getters
normalizedCounter(state, getters) {
const finalCounter = getters.finalCounter;
if (finalCounter < 0) {
return 0;
}
if (finalCounter > 100) {
return 100;
}
return finalCounter;
},
}
});
const app = createApp(App);
app.use(store);
app.mount('#app');
2、使用
computed: {
counter() {
return this.$store.getters.finalCounter;
}
},
computed: {
counter() {
return this.$store.getters.normalizedCounter;
}
},
标签:Introducing,203,counter,return,Getting,app,getters,state,finalCounter
From: https://blog.csdn.net/KevinHuang2088/article/details/142264761