current position:Home>Correctly use the auxiliary functions in vuex in vue3
Correctly use the auxiliary functions in vuex in vue3
2021-08-27 09:42:36 【pfzzz】
Preface
In actual development , We often use vuex
To manage data , With more and more data , We gradually began to use some grammar sugar to help us develop . namely vuex Medium mapState、mapGetters、mapMutations、mapActions
Such auxiliary functions are often used by us .
Use of auxiliary functions
stay vue2 We can pass options API stay computed To use mapState,
computed: mapsState(['name','age'])
Copy code
stay vue3 It is mainly used in setup To operate , Generally used vuex This is how the data in , adopt useStore Use this hook to get
import { useStore } from 'vuex'
import { computed } from 'vue'
setup() {
const store = useStore()
const name = computed(() => store.state.name)
const age = computed(() => store.state.age)
return {
name, age
}
},
Copy code
The disadvantage is that if there are too many data , Then writing is particularly troublesome , So we thought of auxiliary functions mapState To solve . But what? ,vuex There are no official examples of how to setup To use auxiliary functions mapState. So I tried to vue2 In the form of :
setup() {
const stateStore = mapState(['name', 'age'])
return {
...stateStore
}
},
Copy code
But the result displayed in the browser is like this :
Why does it return a function ?
Why is it setup Use in mapState Will return the function ?
I tried to have a look mapState Source code , Discovery is through this.$store
Come and get it store The value of the
However, in setup You can't get this Of
Other auxiliary functions (mapGetters、mapMutations、mapActions) Similarly, they are handled in a similar way . So through the above source code , We know : An auxiliary function returns an object , and key Is string , val Namely function , Be similar to :
computed:{
...mapState(['name','age'])
}
// Convert to :
{
name: function(){},
age:function(){}
}
Copy code
So you can see why a function is returned in the above code .
Encapsulates a useState function
After understanding its principle , We knew it was computed Can be used in mapState, Because computed It's a function in itself , It takes a function as an argument . We also know that the auxiliary function is It is parsed into an object , The property value in the object is a function .
So can we try to combine these two to encapsulate one hooks To use ?
import { useStore, mapState } from 'vuex'
import { computed } from 'vue'
const useState = function(mapper) {
// mapper: Array | Object
const store = useStore()
// Use auxiliary functions to parse into an object
const storeStateFns = mapState(mapper)
const storeState = {}
// adopt Object.keys Get all the objects key value , Traverse , Take out the corresponding value value , That's the function
Object.keys(storeStateFns).forEach(item => {
// We know that the interior of the auxiliary function is through this.$store To achieve
// setup There is no this, So pass bind To change this The direction of
const fn = storeStateFns[item].bind({$store, store})
// Get the function , Parameters as calculated properties , Finally, stay in an object
storeState[item] = computed(fn)
})
// storeState It's an object , key Is string , value The value is ref object
return storeState
}
export default useState
Copy code
Then use it in the component like this :
setup(){
const stateStore = useState(['name','age']) // It's OK to use the form of objects
return {
...stateStore
}
}
Copy code
So you can do it setup Use auxiliary functions in , How happy to have less code again ~
Encapsulates a useMapper function
alike , It's not just mapState, mapGetters It is also packaged according to the same idea , So a little modification . as follows :
// hooks/useMapper.js
import { computed } from 'vue'
import { mapGetters, mapState, useStore } from 'vuex'
const useMapper = (mapper, mapFn) => {
const store = useStore()
const storeStateFns = mapFn(mapper)
const storeState = {}
Object.keys(storeStateFns).forEach((keyFn) => {
const fn = storeStateFns[keyFn].bind({ $store: store })
storeState[keyFn] = computed(fn)
})
return storeState
}
export const useState = ( mapper) => {
return useMapper(mapper, mapState)
}
export const useGetters = (mapper) => {
return useMapper(mapper, mapGetters)
}
Copy code
Then use it like this :
About mapMutations、mapActions There is no need to package , You can think for yourself
Actually, ha , Use mutaiton and actions Is to call a method in , Therefore, it is directly linked to the attribute value of the auxiliary function .
Consideration in the case of modularity
Just encapsulated useMapper Modularity is not considered , At development time , With more and more kinds of data , Use modules Is inevitable , So we need to be right about what just happened useMapper Go ahead Modular edge processing
as follows : We need the help of vuex Provided createNamespacedHelpers Function to get the attributes in the module
import { computed } from 'vue'
import { mapGetters, mapState, useStore, createNamespacedHelpers } from 'vuex'
const useMapper = (mapper, mapFn) => {
const store = useStore()
const storeStateFns = mapFn(mapper)
const storeState = {}
Object.keys(storeStateFns).forEach((keyFn) => {
const fn = storeStateFns[keyFn].bind({ $store: store })
storeState[keyFn] = computed(fn)
})
return storeState
}
export const useState = (moduleName, mapper) => {
let mapperFn = mapState
if (typeof moduleName === 'string' && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapState
} else {
mapper = moduleName
}
return useMapper(mapper, mapperFn)
}
export const useGetters = (moduleName, mapper) => {
let mapperFn = mapGetters
if (typeof moduleName === 'string' && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapGetters
} else {
mapper = moduleName
}
return useMapper(mapper, mapperFn)
}
Copy code
Use :
setup() {
const storeState = useState(['name', 'age', 'six'])
const storeGetters = useGetters(['counter'])
const homeState = useState('home', ['homeCounter'])
return {
...storeState,
...storeGetters,
...homeState
}
},
Copy code
summary
stay vue2 I'm used to using auxiliary functions , But in vuex Not found in the document vue3 How to use auxiliary functions in , Then keep using computed Come and go package store To get the value , With the increase of data , It's also troublesome to use , So it encapsulates such a function to improve development efficiency .
copyright notice
author[pfzzz],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827094232499w.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich