如何使用插槽实现切换器/视图堆栈组件?

时间:2016-11-30 15:05:40

标签: aurelia aurelia-binding aurelia-templating

我正在尝试在Aurelia中实现'切换器'或'viewstack'组件,这对于向导,​​分页内容和单步执行任务非常有用。这将从一些可能的孩子一次显示单个子组件。我希望使用标记类似于:

<my-switcher>
    <one-component></one-component>
    <two-component></two-component>
    <three-component></three-component>
</my-switcher>

现在,明显的替代方案是:

  1. <compose view-model.bind="currentStep">并将currentStep变量一次指向每个组件。 (+ ves:组件只在访问时被实例化,-ves:需要知道每个组件的路径,所有子项都需要是有效的视图模型)
  2. if.bind='active'中的每个组件的定义中添加slot,并从active类中设置此my-switcher成员。 (+ ves:更容易理解,-ves:组件需要专门编写才能在这里使用)。
  3. 通过@children检索孩子(如果现在可以正常工作?)并手动将Element添加为子DOM元素,然后调用ViewCompiler.enhance。 (-ves:似乎无法让@children工作,更多的自定义代码)
  4. 每个人都觉得有点人为的解决方案。有没有人知道是否可以/应该使用更清洁的方法?

1 个答案:

答案 0 :(得分:1)

结合选项2和3,同时避免否定(不知道为什么你不能让@children工作)。

<强> consumer.html

<my-switcher>
    <my-switcher-item>
        <one-component></one-component>
    </my-switcher-item>
    <my-switcher-item>
        <two-component></two-component>
    </my-switcher-item>
    <my-switcher-item>
        <three-component></three-component>
    </my-switcher-item>
</my-switcher>

我-切换-item.js

export class MySwitcherItem {
    constructor() {
        this.isActive = false;
    }
}

我-切换-item.html

<template show.bind="isActive">
    <slot></slot>
</template>

我-switcher.js

import {children} from 'aurelia-framework';

export class MySwitcher {
    @children('my-switcher-item') items = [];

    // Here you have access to this.items[index].isActive.

    // You can set this value to true or false from this class
    // and make sure only one item's isActive is true.

    // You could add next() and previous() methods to move between
    // the items, etc.
}