我正在尝试从ember 2迁移到ember 3,但我在计算属性方面遇到了问题。
以前,我在组件中有这样的计算属性:
import Ember from 'ember';
totalPrice: Ember.computed('attr1', 'attr2', function() {
return this.attr1 + this.attr2;
})我可以在hbs模板中这样做:
Total : {{totalPrice}}在新版本的ember中,我有如下内容:
import { computed, set } from '@ember/object';
totalPrice: computed('attr1', 'attr2', function() {
return this.attr1 + this.attr2;
})但在模板中,totalPrice属性显示为[object],而不是值。我是不是漏掉了什么?
发布于 2019-03-11 23:07:55
我认为您需要使用function而不是箭头函数,因为使用箭头函数时,this会丢失。
用computed的function保持this对组件实例的引用。
computed('attr1', 'attr2', function() {
return this.attr1 && this.attr2;
})发布于 2019-03-14 17:31:04
下面的代码应该可以正常工作。
如果attr1和attr2是文本。
import { computed } from '@ember/object';
...
totalPrice: computed('attr1', 'attr2', function() {
return `${this.attr1} ${this.attr2}`;
})attr1和attr2是数字。
attr1: 1,
attr2: 2,
totalPrice: computed('attr1', 'attr2', function () {
return this.attr1 + this.attr2;
//(or)
return `${this.attr1 + this.attr2}`;
}),发布于 2019-03-18 14:42:39
下面是一个专门用于ember-cli 3.4的代码片段
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旋转
如果你想把字符串连接在一起,应该是这样的
fooBar: computed('attr3', 'attr4', function() {
let foo = this.attr3 ? this.attr3 : null;
let bar = this.attr4 ? this.attr4 : null;
return `${foo} ${bar}`
}),并且输出将是foo bar
如果您想组合一个数字,请遵循下面的说明
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
希望能有所帮助。
https://stackoverflow.com/questions/55104851
复制相似问题