0

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

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>

我遇到了错误“未捕获(承诺)错误:断言失败:您只能将路径传递给 mut”。如果有人能让我知道这里出了什么问题,我将不胜感激。

4

2 回答 2

4

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

例如,

如果我们改变一个如下的值是有道理的,where capitalizeis a helper:

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

但是,下面的代码片段不适合,因为助手以一种方式返回值!

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

助手也发生了同样的事情,each并且循环的值不能被改变!此代码注释可能对进一步挖掘有用。

您可以更改代码片段以处理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...
}

于 2020-01-31T12:38:40.700 回答
1

弄清楚了。发布完整实施以造福他人。我按照 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}}

于 2020-02-06T00:40:38.957 回答