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?
From the
data()
method, you can reference the component's properties usingthis
.So in your case:
Note that this does not work if you are using an arrow function for assigning your data:
Because
this
will not point to the component. Instead, use a plain function:or using ES6 object method shorthand as Siva Tumma suggested:
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.To assign a data property equal to a props, you can use watcher, as following: