Search code examples
javascriptvuejs2vuexarrow-functions

VueJS: Issue with using this keyword in arrow function


Recently working with VueJS - Vuex and I found the this keyword is confusing. Here the code in one of my components:

  props: {
    name: { type: String, default: '' }
  },
  computed: {
    ...mapState('storeJobNew', {
      factors: (state) => state.job['majors']
    })
  },

It's work fine, until I want to make it dynamic, so the computed.factors is now base on the props.name value.

  props: {
    name: { type: String, default: '' }
  },
  computed: {
    ...mapState('storeJobNew', {
      factors: (state) => state.job[this.name]
    })
  },

Now computed.factors is undefined. After a few hours of Googling, I found out that I shouldn't use arrow function here, and my code look like this:

  props: {
    name: { type: String, default: '' }
  },
  computed: {
    ...mapState('storeJobNew', {
      factors: function (state) { return state.job[this.name] }
    })
  },

So here the question:

  1. Why this keyword in arrow function not working here? (I thought that the this keyword here should be the Vue instance that I was created)

  2. Why I need to write this.name instead of this.props.name to access the value in props?


Solution

  • It is not related to Proxy in any way. The this of the arrow function refers to the context in which the arrow function was created. So if you have something like this:

    Vue.component('component', {
    // ...
      computed: {
        ...mapState('storeJobNew', {
          factors: (state) => state.job[this.name]
        })
      }
    // ...
    }
    
    console.dir(this)
    

    The this of this.name is the same as the one of console.dir(this) because it would be identical to writing:

    var factors = (state) => state.job[this.name]
    
    Vue.component('component', {
    // ...
      computed: {
        ...mapState('storeJobNew', {
          factors: factors
        })
      }
    // ...
    }
    
    console.dir(this)
    

    The context is the one of the closest enclosing function ion which the arrow function was created, or if there is none then the global context.

    And to: Why I need to write this.name instead of this.props.name to access the value in props? that how it is defined by the Vue API. When accessing the values you should not need to distinguish between how why where defined.