How does vuex modularize coding + namespace? Let’s take a brief look at this article, I hope it will be helpful to everyone!
Little a: "Why do you want to enable this? "Shan Yu: "Of course it is to make the code easier to maintain and to make the classification of various data more clear."
小a: "Then how can we achieveModular coding + namespace"
Shanyu: "That's all it takes"
namespaced: true
Put all the things in the Count component and Person component into the store
// Count的相关配置 export default { namespaced: true, actions: { // 奇数加法 jiaodd(context, value) { if (context.state.sum % 2) { context.commit('JIA', value) } }, // 延迟加 jiaWait(context, value) { setTimeout(() => { context.commit("JIA", value) }, 500); }, }, mutations: { JIA(state, value) { state.sum += value }, JIAN(state, value) { state.sum -= value }, }, state: { sum: 0, // 当前和 school: '山鱼小学', subject: '前端', }, getters: { bigSum(state) { return state.sum * 10 } } }
2. After opening the namespace, read the state data
computed: { // 自己读取 personList() { returnthis.$store.state.personAbout.personList; }, sum() { returnthis.$store.state.countAbout.sum; }, }, // 借助mapState读取 computed: { ...mapState("countAbout", ["sum", "subject", "school"]), ...mapState("personAbout", ["personList"]) },
3. After opening the namespace, read the getters data in the component
computed: { // 自己读取 firstName() { returnthis.$store.getters["personAbout/firstPersonName"]; } }, methods: { // 借助mapGetters读取 // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations ...mapMutations('countAbout',{ increment: "JIA", decrement: "JIAN" }), // 对象式 ...mapActions('countAbout',{ incrementOdd: "jiaodd", incrementWait: "jiaWait" }) //对象式 },
4. After opening the namespace, call dispatch
methods: { // 直接dispath addWang() { constpersonObj= { id: nanoid(), name: this.name }; this.$store.dispatch("personAbout/addNameWang", personObj); this.name=""; }, }, //借助mapGetters读取: computed: { ...mapGetters('countAbout',['bigSum']) },
5. After opening the namespace, call commit## in the component #
methods: { // 直接调用 add() { constpersonObj= { id: nanoid(), name: this.name }; this.$store.commit("personAbout/ADD_PERSON", personObj); this.name=""; }, } methods: { // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations ...mapMutations('countAbout',{ increment: "JIA", decrement: "JIAN" }), // 对象式 }, }
vuejs introductory tutorial,Basic Programming Video)
The above is the detailed content of Let's talk about how vuex modularizes coding + namespace. For more information, please follow other related articles on the PHP Chinese website!