Reuben Fischman
Reuben Fischman

Reputation: 1

Passing namespace as variable to vuex-map-fields mapFields function

I'm attempting to pass the namespace/module name to the mapFields function as a variable. The reason is I have a form that acts as both a demographics capture form for a membership database, as well as the demographics form for a member's profile. To prevent the "membership database" from overriding the "profile" I have two modules/namespaces within the store and I want to direct the mapFields function based on the usage of the component.

The parent passes a property to the form, and I use that property in the function call, but get an error: "TypeError: Cannot read property 'mod' of undefined"

Here's what my code looks like:

In the parent component:

<demographics :mod="mod"></demographics>
...
export default {
   ...
   data() {
      return {
         mod: "database"
      }
   },
...

In my child component:

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

if I replace "this.mod" with the explicit 'database' everything will work find.

Any help is appreciated!

Upvotes: 0

Views: 418

Answers (1)

jmmygoggle
jmmygoggle

Reputation: 965

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>>>]),
  }
...

Upvotes: -1

Related Questions