I am passing a props to a component:
{{messageId}}
// other html code
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 }
}
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
}
}
}
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>
<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>
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;
}