问题
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?
回答1:
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;
}
回答2:
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 }
}
回答3:
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
}
}
}
回答4:
<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>
来源:https://stackoverflow.com/questions/42722433/accessing-props-in-vue-component-data-function