Accessing props in vue component data function

vue.jsVue Loader

vue.js Problem Overview


I am passing a props to a component:

    <template>
       {{messageId}}
       // other html code
    </template>
    
    <script>
       export default {
          props: ['messageId'],
          data: function(){
             var theData={
                // below line gives ReferenceError messageId is not defined
                somevar: messageId,
                // other object attributes
             }
          }
       }
    </script>

In above code, I have commented the line that gives the error. If I remove that line, it works as normal and template renders properly (and I can see the expected value of {{messageId}} as well). Hence the logic to pass data is correct.

It seems that the way to access the messageId in data() is wrong. So how do I access the props messageId in data?

vue.js Solutions


Solution 1 - vue.js

From the data() method, you can reference the component's properties using this.

So in your case:

data: function() {
  var theData = {
    somevar: this.messageId,
    // other object attributes
  }

  return theData;
}

Solution 2 - vue.js

EDIT: According to Ryans posts it is possible to reference the instance with an arrow function like this:

data: (instance) => ({
  somevar: instance.messageId 
}),

PREVIOUS POST:

Note that this does not work if you are using an arrow function for assigning your data:

data: () => ({
  somevar: this.messageId // undefined
}),

Because this will not point to the component. Instead, use a plain function:

data: function() {
  return { somevar: this.messageId }
},

or using ES6 object method shorthand as Siva Tumma suggested:

data() {
    return { somevar: this.messageId }
}

Solution 3 - vue.js

To assign a data property equal to a props, you can use watcher, as following:

<script>
   export default {
      props: ['messageId'],
      data: function(){
         var theData={
            somevar: "",
            // other object attributes
         }
      },
      watch: {
        messageId: function(newVal) { 
           this.somevar = newVal
        }
      }
   }

Solution 4 - vue.js

as @Saurabh described, I want to add more details.

If you are rendering a Child component, and want to set the data variables by props, you have to use both this and watch functions:

Step1. use this to access the props variables.

<script>
export default {

    data () {
      id: 0
    },
    
  
    props: ['propId'],
    methods: {
      init() { 
        this.id = this.propId  // step1. assign propId to id
      }
    }
}
</script>

Step2. watch the props variable

<script>
export default {

    data () {
      id: 0
    },
    props: ['propId'],
    methods: {
      init() { 
        this.id = this.propId  // step1. assign propId to id
      }
    },
    // add this to your code , this is a MUST. 
    // otherwise you won't SEE your data variable assigned by property
    watch { 
      propId: function(new_value) { 
        this.init()
      }
    }
}
</script>

Step3. understand the process of rendering Child component

Assuming you have two component: Parent and Child ( Child has a property naming as propId ) , and Child also have a "async" operation such as reading database.

// Parent's View

<Child propId='parent_var_id'></Child>

3.1 Parent got rendered

3.2 Child got rendered , in this case, parent_var_id blank

3.3 10ms later, parent_var_id changed to 100

3.4 Child property propId also changed as binding.

3.5 Child 's watch function called, and the variable id defined in data changed.

Solution 5 - vue.js

<template>
   {{messaged}}
   // other HTML code
</template>

<script>
   export default {
      props: ['messaged'],
      data: function(){
         return () {
           some_var: this.messaged
         }
      },
      methods: {
      post_order: function () {
        console.log({
          some_var: this.some_var.id
        })
      }
    }

   }
</script>

Solution 6 - vue.js

I think you have done your solution since the question posted a couple of month earlier. I faced the same problem yesterday, so tried out above solutions without no luck. However, I would like to share an alternative solution for this case that helps someone considerably. watch has some attributes to handle those type of cases. Below scrips shows that how do we accept the props value is data.

<script>
   export default {
      props: {
            messageId: {
                type: String,
                required: true
            }
        }
      data: function(){
         var theData= {
            somevar: "",
            // other object attributes
         }

         return theData;
      },
      watch: {
        messageId: {
                // Run as soon as the component loads
                immediate: true,
                handler() {
                    // Set the 'somevar' value as props
                    this.somevar = this.messageId;
                }
            }
      }
   }
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrahulserverView Question on Stackoverflow
Solution 1 - vue.jsthanksdView Answer on Stackoverflow
Solution 2 - vue.jsmufasaView Answer on Stackoverflow
Solution 3 - vue.jsSaurabhView Answer on Stackoverflow
Solution 4 - vue.jsSiweiView Answer on Stackoverflow
Solution 5 - vue.jsChinedu OhagwuView Answer on Stackoverflow
Solution 6 - vue.jsNazmus ShakibView Answer on Stackoverflow