rah*_*ver 45 vue.js vue-loader
我将道具传递给组件:
<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>
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我已经评论了产生错误的行.如果我删除该行,它将正常工作并且模板呈现正确(我也可以看到{{messageId}}的预期值).因此传递数据的逻辑是正确的.
似乎访问messageIdin data()的方式是错误的.那么如何访问messageId数据中的道具呢?
tha*_*ksd 39
从该data()方法中,您可以使用引用组件的属性this.
所以在你的情况下:
data: function() {
var theData = {
somevar: this.messageId,
// other object attributes
}
return theData;
}
Run Code Online (Sandbox Code Playgroud)
muf*_*asa 16
请注意,如果您使用箭头功能分配数据,则此方法不起作用:
data: () => ({
somevar: this.messageId // undefined
}),
Run Code Online (Sandbox Code Playgroud)
因为this不会指向该组件。而是使用一个普通函数:
data: function() {
return { somevar: this.messageId }
},
Run Code Online (Sandbox Code Playgroud)
或使用Siva Tumma建议的ES6对象方法速记:
data() {
return { somevar: this.messageId }
}
Run Code Online (Sandbox Code Playgroud)
要分配一个等于props的数据属性,可以使用watcher,如下所示:
<script>
export default {
props: ['messageId'],
data: function(){
var theData={
somevar: "",
// other object attributes
}
},
watch: {
messageId: function(newVal) {
this.somevar = newVal
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41348 次 |
| 最近记录: |