【问题标题】:Dynamically add custom component to loaded DOM (aurelia.js)将自定义组件动态添加到加载的 DOM (aurelia.js)
【发布时间】:2017-07-05 19:11:55
【问题描述】:

是否可以在 DOM 加载后添加自定义组件?

例如点击按钮时

模板

<template>
    <button click.delegate="add_component()"> Press me </button>
</template>

视图模型

@inject(Element)

export class App {

  constructor(element) {
      this.element = element;
  }

  function add_component() {
     var component = document.createElement('<customElement></customElement>');
     this.element.appendChild(component);
  }
}

【问题讨论】:

  • 答案是肯定的还是否定的,这取决于你想要做什么。不可能按照您显示的方式做您正在做的事情,因为 Aurelia 不会像那样寻找添加到 DOM 中的东西。但是,如果您使用中继器和 compose 元素,您可以做一些类似于您想做的事情。您可能想重新考虑您正在做什么,看看是否有更好的方法在 MVVM 模式的范围内完成它。
  • 添加到 Ashley 的评论中,您可以按照在 aurelia-dialog 中完成的方式动态渲染组件,或者像 aurelia-notify 这样的 toast 插件。

标签: javascript aurelia


【解决方案1】:

实际上,有不止一种方法可以做到这一点。根据您的实际需要,如果您需要动态切换视图,则可以使用compose element

另一种方法是使用 Aurelia 的 View Compiler 将标记编译成一个视图,然后创建一个 View Slot(在 aurelia-templating GitHub issue 中有一些关于该主题的讨论)。使用 View Slots,应该可以一个接一个地动态添加多个视图。

但是,如果您的实际需求与您的示例相近,您可以简单地使用以下方法:

<template>
    <button click.delegate="add_component()"> Press me </button>
    <custom-element if.bind="hasCustomElement"></custom-element>
</template>

在视图中:

export class App {
  @observable hasCustomElement = false;

  function add_component() {
      this.hasCustomElement = true;
  }
}

在视图模型中。只有当if.bind 条件变为true 时,自定义元素才会附加到dom 中,如果变为false,则将其删除。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 1970-01-01
  • 2018-07-03
相关资源
最近更新 更多