[Vuejs]-Passing namespace as variable to vuex-map-fields mapFields function

-1👍

When mapFields is called, the context of this changes because of the way mapFields internals are designed. (e.g. An internal arrow function inherits the enclosing scope’s this instead of your external this)

You’ll need to establish a value that can preserve the reference to your mod value via your component’s this context. How best to do this depends on your needs/preferences. There is a quirky suggestion in a vuex-map-fields GitHub issue that involves remapping this to a self variable during the beforeCreate lifecycle hook but it was reported to have certain limitations.

let self;
export default {
...
  props: ['mod'],
  computed: {
     ...mapFields(self.mod, [<<<FIELDS HERE>>>]),
  },
  beforeCreate() { self = this },
...

Alternatively, you could supply your mod value outside of the this context of the component such as importing a context-specific mod constant rather than passing it down as a prop through descendant components.

import { PARENT_CONTEXT_MOD } from '../../ParentContext/module/consts.js'

export default {
...
  props: ['mod'],
  computed: {
     ...mapFields(PARENT_CONTEXT_MOD, [<<<FIELDS HERE>>>]),
  }
...

Leave a comment