【问题标题】:ember component increment/decrement valueember 组件增量/减量值
【发布时间】:2017-12-28 20:40:34
【问题描述】:

我被组件 js 中的值递增和递减所困扰。我在我的模板中得到了这个:

<div class="circleBase" {{action 'upHeat' device.status}}> <p>  {{heat}} C </p> </div>

现在我只想在单击 div 时增加热值。我的组件如下所示:

    init() {
        console.log('init');
        this._super(...arguments);
        this.errors = [];
      },
      didRender() {
        this.setProperties({
          heat: 0
        });
      },
    actions: {
        upHeat: function(a){
            this.set('heat', this.heat +1)
            //or
            this.setProperties({
                heat: this.heat +1
              });
           console.log(heat);
        }
      }

这不起作用。每次我点击我的 div 时,热值都会增加但不会保存。我的模板仍然显示 0 作为值。

【问题讨论】:

    标签: javascript ember.js ember-cli


    【解决方案1】:

    您已重置didRender() 中的值。

    因此钩子将触发渲染,将值重置为0

    didRender 中使用console.log(something) 可以查看每当单击div 时都会调用didRender 挂钩。

    我根据您的要求创建了一个小玩意儿。请看一下。

    https://ember-twiddle.com/5ef763cc77aec803f9d62ae85a15dbc1

    【讨论】:

      【解决方案2】:

      你不应该在 Ember 中读取像 this.heat 这样的值,而是使用 this.get('heat')。所以这对你有用:

      this.set('heat', this.get('heat') + 1);
      

      如果你只是想增加一个属性,还有另一个例子,你可以像这样使用this.incrementProperty

      this.incrementProperty('heat');
      

      您可以在API docs阅读。

      【讨论】:

      • 我尝试了您的建议,但它仍然只是增加了我的组件 js 中的值,以便像我的版本一样执行此操作调用。模板仍然显示 0。
      • OP 请在问题中更新您的代码 sn-p,以便我们可以看到您尝试了什么,并在您完成此操作后告诉我们。此外,初始值根本不需要 didRender/setProperties。如果您希望 heat 的初始值为 0,您可以在组件 js 对象样板内执行 heat:0。
      • 哦,现在我明白了,您正在将 didRender 中的值重置为 0。因此,您的值将更新,这将触发渲染,然后在渲染后将值重置为 0,以便再次渲染并删除该值。如果我们不这样做,它就会起作用。 jsbin.com/yohewut/edit?html,js,output
      猜你喜欢
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2013-01-19
      • 2012-03-27
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      相关资源
      最近更新 更多