102

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?

Michael T
  • 370
  • 4
  • 16
rahulserver
  • 10,411
  • 24
  • 90
  • 164

6 Answers6

98

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;
}
thanksd
  • 54,176
  • 22
  • 157
  • 150
69

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 }
}
mufasa
  • 1,271
  • 13
  • 18
  • 5
    Instead why not use `data() {..}` – Siva Tumma May 02 '19 at 09:16
  • 2
    I got burned by this once. It's a subtle difference but switching the function from arrow to data() {return {}} does the trick. Thanks mufasa. – Sean Rasmussen Dec 31 '19 at 19:42
  • Thanks a lot, was looking for it. – Loïc Monard Jul 17 '20 at 13:19
  • Thank you. This was very helpful. – vbuser2004 Sep 14 '20 at 23:49
  • 1
    You can use an arrow function actually— the first argument will be a reference to the instance. `data: vm => ({ somevar: vm.messageId })` – Ryan Feb 18 '21 at 16:58
  • I know I'm late to the party but this answer solved an issue I just ran into. My understanding (albeit probably wrong now obviously) was that all three function declarations are the same, just difference in syntactic sugar. I'll research this but if someone want to drop a hint I won't complain. – jvndev Mar 13 '21 at 15:00
  • 1
    @jvndev Yes, the two bottom ones are the same and the top one is an arrow function which handles the context differently – mufasa Mar 15 '21 at 07:31
15

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
        }
      }
   }
Saurabh
  • 71,488
  • 40
  • 181
  • 244
3

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.

Siwei
  • 19,858
  • 7
  • 75
  • 95
0
<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>
0

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>
Nazmus Shakib
  • 802
  • 1
  • 9
  • 18