首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >3计算属性

3计算属性
EN

Stack Overflow用户
提问于 2019-03-11 23:06:30
回答 3查看 73关注 0票数 0

我正在尝试从ember 2迁移到ember 3,但我在计算属性方面遇到了问题。

以前,我在组件中有这样的计算属性:

代码语言:javascript
复制
import Ember from 'ember';

totalPrice: Ember.computed('attr1', 'attr2', function() {
    return this.attr1 + this.attr2;
})

我可以在hbs模板中这样做:

代码语言:javascript
复制
Total : {{totalPrice}}

在新版本的ember中,我有如下内容:

代码语言:javascript
复制
import { computed, set } from '@ember/object';

totalPrice: computed('attr1', 'attr2', function() {
   return this.attr1 + this.attr2;
})

但在模板中,totalPrice属性显示为[object],而不是值。我是不是漏掉了什么?

EN

回答 3

Stack Overflow用户

发布于 2019-03-11 23:07:55

我认为您需要使用function而不是箭头函数,因为使用箭头函数时,this会丢失。

用computed的function保持this对组件实例的引用。

代码语言:javascript
复制
computed('attr1', 'attr2', function() {
   return this.attr1 && this.attr2;
})
票数 0
EN

Stack Overflow用户

发布于 2019-03-14 17:31:04

下面的代码应该可以正常工作。

如果attr1attr2是文本。

代码语言:javascript
复制
import { computed } from '@ember/object';
...
totalPrice: computed('attr1', 'attr2', function() {
  return `${this.attr1} ${this.attr2}`;
})

attr1attr2是数字。

代码语言:javascript
复制
attr1: 1,
attr2: 2,
totalPrice: computed('attr1', 'attr2', function () {
  return this.attr1 + this.attr2;
  //(or)
  return `${this.attr1 + this.attr2}`;
}),
票数 0
EN

Stack Overflow用户

发布于 2019-03-18 14:42:39

下面是一个专门用于ember-cli 3.4的代码片段

代码语言:javascript
复制
import Controller from '@ember/controller';
import { computed } from '@ember/object';

export default Controller.extend({
  appName: 'Ember sdfa',

  attr1: 1,
  attr2: 2,
  attr3: 'foo',
  attr4: 'bar',
  attr5: 3,
  attr6: 4,

  totalPrice: computed('attr1', 'attr2',function() {
    let a = this.attr1 ? this.attr1 : 0;
    let b = this.attr2 ? this.attr2 : 0;
    let total = a + b;

    return total;
  }),
});

这对于获取totalPrice应该是有效的,这是你可以在https://ember-twiddle.com/8801e28a888b469b8057d67a63829808?openFiles=controllers.application.js%2C周围使用的ember旋转

如果你想把字符串连接在一起,应该是这样的

代码语言:javascript
复制
  fooBar: computed('attr3', 'attr4', function() {
    let foo = this.attr3 ? this.attr3 : null;
    let bar = this.attr4 ? this.attr4 : null;

    return `${foo} ${bar}`
  }),

并且输出将是foo bar

如果您想组合一个数字,请遵循下面的说明

代码语言:javascript
复制
combinedNumber: computed('attr5', 'attr6', function() {
    let a = this.attr5 ? this.attr5 : null;
    let b = this.attr6 ? this.attr6 : null;

    return `${a} ${b}`
  }),

combineNumber的输出是3 4

希望能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55104851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档