Encapsulate mapState and mapGetters

MapState and mapGetters are encapsulated in the CompusitionsAPI

  • The setup function does not have this, and any this is meaningless
  • deconstructedmapStateandmapGettersIs a function, not an object

There is no need to encapsulate mapState and mapGetters in OptionsAPI

  • deconstructedmapStateandmapGettersThe function,Computed propertiesIt automatically gets the return value

Two files are encapsulated

  • proStateStore.js:mapStateandmapGettersThe encapsulation
import {mapState, mapGetters, createNamespacedHelpers } from 'vuex'
import  {proMapper}  from 'proMapper.js'

export const proGetters=function(spaceName,mapArry){
  let mapFn = mapGetters
  if (typeof spaceName === 'string' && spaceName.length > 0) {
    mapFn = createNamespacedHelpers(spaceName).mapGetters
  } else {
    mapArry = spaceName
  }
  return proMapper(mapArry, mapFn)
}

export const proState=function(spaceName, mapArry) {
  let mapFn = mapState
  if (typeof spaceName === 'string' && spaceName.length > 0) {
    mapFn = createNamespacedHelpers(spaceName).mapState
  } else {
    mapArry = spaceName
  }
  return proMapper(mapArry, mapFn)
}
Copy the code
  • proMapper.js:mapStateandmapGettersEncapsulation of common traversal functionality
import { useStore } from "vuex";
import { computed } from "@vue/reactivity";
export const promapArry= function(mapArry,mapFn){
  const store=useStore()
  const stateStoreFn=mapFn(mapArry)
  let stateStore={}
  Object.keys(stateStoreFn).forEach(item= >{
    const fn=stateStoreFn[item].bind({$store:store})
    stateStore[item]=computed(fn)
  })
  return stateStore
}
Copy the code

Encapsulation is necessary for decoupling large projects, and if there are not many attributes in the component, lengthy encapsulation makes reading difficult

Use destruct assignment

Using the deconstructed assignment of the object, you can get all the attributes, which is easier to read 🐕🐕🐕

<script>
import { useStore } from "vuex"
export default{
  setup(){
    const store=useStore()
    return{... store.getters, ... store.state } } }</script>
Copy the code

The deconstructed value is not reactive

  • Using Reactive Wrappinglet counter=reactive({... store.state})
    • Simultaneously availabletoRefsTo unpack
  • Wrap individual values with ref
let{counter} = {... store.state}let counter=ref(counter)
Copy the code