Accessing props in vue component data function

rahulserver picture rahulserver · Mar 10, 2017 · Viewed 84.7k times · Source

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?

Answer

thanksd picture thanksd · Mar 10, 2017

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;
}