【问题标题】:How to mutate an array's value in "each" helper in Ember JS (Octane)如何在 Ember JS (Octane) 的“每个”助手中改变数组的值
【发布时间】:2020-01-30 03:52:29
【问题描述】:

我有一个字符串数组作为参数传递给组件,在组件内部我使用“每个”帮助器来呈现文本输入中的每个字符串。我尝试了以下方法。

MainComponent.hbs
<Component @model={{model}}/>

//Eg: model.list = ["Jack", "Sparrow"];

Component.hbs
<div>
    {{#each this.args.model.list as |name|}}
    <div>           
         <PaperInput @value={{ name }} 
            @placeholder="Enter a Name"
            @onChange={{action (mut name)}}/>        
    </div>
    {{/each}}
</div>

我遇到了错误“Uncaught (in promise) Error: Assertion Failed: You can only pass a path to mut”。如果有人能告诉我这里出了什么问题,我将不胜感激。

【问题讨论】:

    标签: ember.js ember-cli ember-octane


    【解决方案1】:

    从助手派生的值(在您的情况下为 each)不能使用 mut 助手进行变异,因为助手通常不会传递或保留值来更改原始属性。

    例如,

    如果我们改变一个值如下,capitalize 是一个助手,这是有意义的:

    <button {{action (mut name) (capitalize name)}}>
     Capitalize
    </button>
    

    然而,下面的 sn-p 不适合,因为 helper 以一种方式返回值!

    <button {{action (mut (capitalize name)) name}}>
     Capitalize
    </button>
    

    each 助手也发生了同样的事情,循环的值不能被改变!这个code comment 可能对进一步挖掘有用。

    您可以更改您的 sn-p 以处理支持组件类中的 onChange

    <div>
        {{#each this.args.model.list as |name index|}}
        <div>           
             <PaperInput @value={{ name }} 
                @placeholder="Enter a Name"
                @onChange={{this.changeName index}}/>        
        </div>
        {{/each}}
    </div>
    
    // component.js
    
    changeName(index, nameToBeUpdated) {
     // change the name here...
    }
    
    

    【讨论】:

    • 谢谢 Gokul。您将如何更新 changeName 中的数组以使其重新呈现?
    • 例如 this.args.model.list[index] = name 不起作用。
    • 这就是该跟踪系统现在在 Ember octane 中的工作方式。这个SO answer 应该会有所帮助。此外,在 octane 指南中的属性跟踪中有a section,它解释了另一种方法!
    • 想通了。发布了完整的实现:)
    【解决方案2】:

    想通了。发布完整实施以造福他人。我按照 Gokul 的回答中的建议将索引值传递给组件的操作,但遇到了另一个问题。没有直接的方法来更改数组的值。所以我使用了可变数组的替换方法来做到这一点。这又引起了另一个问题,每次我在文本输入中输入一个字符时,它都会改变数组值并重新渲染列表,从而将焦点从输入中移开。因此,在“每个”助手中,我必须设置 key="@index",它告诉助手仅在数组索引更改而不是值更改时重新渲染。

    Component.js
    
    @action
     updateName( index, name ) {
        this.args.model.list.replace(index, 1, [name]);     
     }
    MainComponent.hbs
    
    <Component @model={{model}}/>
    
    
    Component.hbs
    
    {{#each this.args.model.list key="@index" as |name index|}}
        <div>           
             <PaperInput @value={{ name }} 
                @placeholder="Enter a Name"
                @onChange={{action this.updateName index}}/>        
         </div>
    {{/each}}

    【讨论】:

      猜你喜欢
      • 2017-06-03
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多