gpt4 book ai didi

aurelia - 如何动态添加和删除自定义元素或通过 aurelia 中的单击事件添加和删除自定义元素

转载 作者:行者123 更新时间:2023-12-02 18:22:31 26 4
gpt4 key购买 nike

几乎要放弃 Aurelia,我正在努力在 Aurelia 中动态添加自定义元素,假设我们有一个自定义标签:查看 my-element.html:

<template>  My Element ${name} </template>

View 模型:my-element.js:

export class MyElement {
@bindable name = '';
}

所以我尝试在另一个 View 中手动添加此标签:

<template>
<button type="button" click.delegate="createMyElement()">Remove</button>
</template>

另一个 View 模型:

export class App {

createMyElement() {
//how to do it in here to create element
//<my-element name='name1'></my-element>
}
}

我查看了此链接https://gist.run/?id=762c00133d5d5be624f9 ,但它需要一个容器引用
<div ref="container"></div>

我不想指定容器,而是希望将其附加到当前 View 。

我还尝试使用 https://github.com/gooy/aurelia-compiler 中的 aurelia-compiler ,当我尝试导入它时,它能够找到文件“gooy/aurelia-compiler”,但我收到此错误:调用编译器时出错。您是否正在尝试注入(inject)/注册 DI 中不存在的内容?

有人可以帮忙吗?谢谢。

最佳答案

您可以注入(inject) View 的 html 元素并将其用作“容器”。像这样:

import {inject} from 'aurelia-framework';
import {ViewFactory} from './view-factory';

@inject(Element, ViewFactory)
export class App {
//...

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

然后,在插入方法中使用this.element:

this.dispose = this.viewFactory.insert(this.element, this.viewHtml, viewModel);

运行示例:

https://gist.run/?id=9d5e7a60cd02e55618829a304df00621

希望这有帮助!

关于aurelia - 如何动态添加和删除自定义元素或通过 aurelia 中的单击事件添加和删除自定义元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com