简体   繁体   English

在 Vue.js 中,为什么我的计算属性不起作用

[英]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/ https://jsfiddle.net/hk49eL38/

if I replace:如果我更换:

this.myMessage with a string (eg "Hello world"), it renders correctly. this.myMessage带有一个字符串(例如“Hello world”),它会正确呈现。

But when I use this.myMessage , no text is rendered.但是当我使用this.myMessage时,不会呈现任何文本。

Why is this?为什么是这样?

The problem is that you are trying to use the computed property as the initial value of the message data property.问题是您试图使用计算属性作为message数据属性的初始值。

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.当 Vue 内部调用data函数时,计算的属性还没有被评估,这是很早就完成的,在created钩子之前。

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 .如果您尝试在beforeCreated钩子(第一个生命周期钩子)中记录计算属性的值,而不是像您的示例中那样mounted ,您将看到它是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).计算的属性值不能用作data属性的初始值,通常它们取决于data属性值和其他外部和反应值(例如 Vuex getter、Vue 路由器参数等)。

You shouldn't use this before writing myMessage , as VueJS doesn't work like that.在编写myMessage之前你不应该使用this ,因为 VueJS 不是这样工作的。 It already considers everything in this context.它已经考虑了this方面的一切。 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.尝试在安装组件时将myMesssage的值设置为message

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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