简体   繁体   中英

In Vue.js, why isn't my computed property working

In the following code:

 new Vue({ el: '#app', computed: { myMessage: function() { return "hello"; } }, data: { message: this.myMessage }, mounted: function() { console.log(this.myMessage); } })
 <script src="https://unpkg.com/vue"></script> <div id="app"> <p>{{ message }}</p> </div>

https://jsfiddle.net/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?

The problem is that you are trying to use the computed property as the initial value of the message data property.

When the data function is called internally by Vue, the computed properties haven't been evaluated yet, this is done very early, before the created hook.

If you try to log the value of the computed 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 component 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 (eg 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.com/vue"></script>

<div id="app">
  <p>{{ myMessage }}</p>
</div>

Try setting the value of myMesssage to message when component is mounted.

mounted: function() {
    this.message = this.myMessage
}

尝试更改计算出的我的消息中的数据消息

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM