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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744779820a4593267.html
评论列表(0条)