admin管理员组文章数量:1392110
In the following code:
new Vue({
el: '#app',
puted: {
myMessage: function() {
return "hello";
}
},
data: {
message: this.myMessage
},
mounted: function() {
console.log(this.myMessage);
}
})
<script src=""></script>
<div id="app">
<p>{{ message }}</p>
</div>
In the following code:
new Vue({
el: '#app',
puted: {
myMessage: function() {
return "hello";
}
},
data: {
message: this.myMessage
},
mounted: function() {
console.log(this.myMessage);
}
})
<script src="https://unpkg./vue"></script>
<div id="app">
<p>{{ message }}</p>
</div>
https://jsfiddle/hk49eL38/
if I replace:
this.myMessage
with a string (eg "Hello world"), it renders correctly.
But when I use this.myMessage
, no text is rendered.
Why is this?
Share Improve this question edited Apr 27, 2019 at 12:18 Daniel Beck 21.5k5 gold badges43 silver badges60 bronze badges asked Apr 27, 2019 at 3:42 MaryMary 1,1554 gold badges22 silver badges46 bronze badges 1-
Think of it like this:
data
is where you store you initial values,puted
is like the name says, results of some putation. – Rudy Commented Apr 27, 2019 at 9:55
4 Answers
Reset to default 8The problem is that you are trying to use the puted property as the initial value of the message
data property.
When the data
function is called internally by Vue, the puted properties haven't been evaluated yet, this is done very early, before the created
hook.
If you try to log the value of the puted property in the beforeCreated
hook (the first life-cycle hook) instead of the mounted
as in your example, you will see that it is undefined
.
See the ponent life-cycle:
(*) Diagram cropped for brevity
Computed properties are evaluated in the "Init injections & reactivity" step in the above diagram.
Computed property values cannot be used as the initial value of a property of data
, and normally they depend on data
property values and other external and reactive values (e.g. Vuex getters, Vue router parameters, etc).
You shouldn't use this
before writing myMessage
, as VueJS doesn't work like that. It already considers everything in this
context. You should do it like this:
<script src="https://unpkg./vue"></script>
<div id="app">
<p>{{ myMessage }}</p>
</div>
Try setting the value of myMesssage to message when ponent is mounted.
mounted: function() {
this.message = this.myMessage
}
Try to change the data message in the puted my message
本文标签: javascriptIn Vuejswhy isn39t my computed property workingStack Overflow
版权声明:本文标题:javascript - In Vue.js, why isn't my computed property working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744779818a2624639.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论