【问题标题】:Aurelia custom element - $parent undefinedAurelia 自定义元素 - $parent undefined
【发布时间】:2018-03-27 19:11:43
【问题描述】:

我有带有中继器的模板:

<template repeat.for="i of 2">
    <template repeat.for="j of 2">
        <p>${ $parent.$index } - ${ $index }</p>
    </template>
</template>

打印结果:

0 - 0
0 - 1
1 - 0
1 - 1

如果我使用自定义元素 child-item 和相同的模板:

<template>
    <p>${ $parent.$index } - ${ $index }</p>
</template>

并使用child-item 编写我的原始示例:

<template repeat.for="i of 2">
    <child-item repeat.for="j of 2"></child-item>
</template>

结果只有:

-
-
-
-

有没有办法将 $parent 和 $index 透明地传播到child-item

更新

在尝试了一些建议后,我最接近的是:

<template repeat.for="i of 2">
    <child-item repeat.for="j of 2" parent-index.bind="$parent.$index" index.bind="$index"></child-item>
</template>

child-item 模板的样子:

<template bindable="parentIndex, index">
    <p>${ parentIndex } - ${ index }</p>
</template>

$parent 上下文直接与parent.bind="$parent" 绑定不起作用。必须直接绑定父索引。使用这种方法,任何与$parent.$parent.$index 内联的东西都无法实现。

【问题讨论】:

    标签: javascript aurelia aurelia-templating


    【解决方案1】:

    这样的事情会起作用

    子项.ts:

    import { customElement, bindable } from 'aurelia-framework';
    
        @customElement('child-item')
        export class ChildItem {
          @bindable index;
        }
    

    子项.html

    <template>
        <p>${ index }</p>
    </template>
    

    带有中继器的模板:

    <template>
        <require from="./child-item">
    
        <child-item repeat.for="child of childred" index.bind="$index"></child-item>
    </template>
    

    【讨论】:

    • $index 通过overrideContext in bind(bindingContext: Object, overrideContext: Object) 传递给自定义元素。所以$index默认工作,不需要手动绑定。问题是如何使$parent 可用。
    • 从您的代码中不清楚您需要$parent 做什么? bindingContext 虽然是父级
    • 在尝试了您和@ashley-grant 的建议后,我修改了问题以使其更加清晰并添加了更新。我还必须按照您的建议绑定索引。
    【解决方案2】:

    您需要使用数据绑定来传递它。将parentindex 可绑定属性添加到child-item 视图模型。

    【讨论】:

    • 你能举个简单的例子吗? index.bind="$index" 似乎合乎逻辑,但当前绑定上下文的价值应该是什么? parent.bind="..."?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2016-12-31
    • 1970-01-01
    相关资源
    最近更新 更多