Let"s talk about my business scenario first. I now have two pages An and B, and the
A page has two sub-components A1 and a2. A specific component is displayed through the isComponent of vuex
A.vue is as follows:
<template>
<div class="box">
<keep-alive>
<component :is="isComponent"></component>
</keep-alive>
</div>
</template>
<script>
// a1
import a1 from "./a1";
// a2
import a2 from "./a2";
import { mapState } from "vuex";
export default {
data () {
return {};
},
computed: {
...mapState({
isComponent: state => state.a.isComponent
})
},
components: {
a1,
a2
},
methods: {},
created () {
this.$store.commit("setComponent", "a1");
}
};
</script>
The code for the vuex file a.js of the A page is as follows:
export default {
state () {
return {
//
isComponent: ""
};
},
gettters: {},
mutations: {
//
setComponent: (state, componentName) => {
state.isComponent = componentName;
}
}
};
The code corresponding to B page is similar to that of A page
B.vue as follows:
<template>
<div class="box">
<keep-alive>
<component :is="isComponent"></component>
</keep-alive>
</div>
</template>
<script>
// b1
import b1 from "./b1";
// b2
import b2 from "./b2";
import { mapState } from "vuex";
export default {
data () {
return {};
},
computed: {
...mapState({
isComponent: state => state.b.isComponent
})
},
components: {
b1,
b2
},
methods: {},
created () {
this.$store.commit("setComponent", "b1");
}
};
</script>
The code for the vuex file b.js of the B page is as follows:
export default {
state () {
return {
//
isComponent: ""
};
},
gettters: {},
mutations: {
//
setComponent: (state, componentName) => {
state.isComponent = componentName;
}
}
};
there may be C, D, E. On the page, ask: the code in a.js in vuex is basically the same as that in b.js. How can you avoid duplicating code?