Aurelia 在运行时更改元素类型
是否可以在运行时在自定义组件模板中动态定义元素的类型 在以下示例中,我希望避免重复Aurelia 在运行时更改元素类型,aurelia,aurelia-templating,Aurelia,Aurelia Templating,是否可以在运行时在自定义组件模板中动态定义元素的类型 在以下示例中,我希望避免重复按钮和a元素的内部内容: <template> <button if.bind="!isLinkBtn"> <span class="btn-icon">${icon}</span> <span class="btn-text">${contentText}</span> </button&
按钮
和a
元素的内部内容:
<template>
<button if.bind="!isLinkBtn">
<span class="btn-icon">${icon}</span>
<span class="btn-text">${contentText}</span>
</button>
<a if.bind="isLinkBtn">
<!--
The content is a 1:1 duplicate of the button above which should be prevented
somehow in order to keep the view DRY
-->
<span class="btn-icon">${icon}</span>
<span class="btn-text">${contentText}</span>
</a>
</template>
${icon}
${contentText}
. 即使已经提供了可能的解决方案,我还是希望看到一些更简单的方法来解决这个问题;) 如果要重用HTML代码段,请使用compose。这样做不会创建新的自定义元素。它只是在每个compose元素的位置包含HTML。因此,包含的HTML的视图模型与组成它的元素的视图模型相同
看看这个GistRun:
自定义链接.html
<template>
<button if.bind="!isLinkBtn">
<compose view="./custom-link-icon-and-text.html"></compose>
</button>
<a if.bind="isLinkBtn" href="#">
<compose view="./custom-link-icon-and-text.html"></compose>
</a>
</template>
<template>
<span class="btn-icon">${icon}</span>
<span class="btn-text">${contentText}</span>
</template>
<template>
<require from="./custom-link"></require>
<custom-link content-text="Here is a button"></custom-link>
<custom-link is-link-btn.bind="true" content-text="Here is a link"></custom-link>
</template>
自定义链接图标和文本.html
<template>
<button if.bind="!isLinkBtn">
<compose view="./custom-link-icon-and-text.html"></compose>
</button>
<a if.bind="isLinkBtn" href="#">
<compose view="./custom-link-icon-and-text.html"></compose>
</a>
</template>
<template>
<span class="btn-icon">${icon}</span>
<span class="btn-text">${contentText}</span>
</template>
<template>
<require from="./custom-link"></require>
<custom-link content-text="Here is a button"></custom-link>
<custom-link is-link-btn.bind="true" content-text="Here is a link"></custom-link>
</template>
对不起,我在看gitter的时候同时做了两件事,显然我不擅长:-)
对于你最终想要完成的事情,这也能起作用吗
我不是一名专家,也不是这方面的很多知识,但据我所知,这将实现你想要的。浏览器将查看角色属性,并将其作为链接或按钮处理,忽略实际的元素类型本身/不关心它是按钮还是锚点-它将充当角色中定义的类型
然后,您可以使用css将其样式设置为按钮或链接标记
<a role.bind="type"><span>x</span><span>y</span></a>
processContent
在这种情况下不会有帮助,因为它无法访问视图模型的属性(如isLinkBtn
)。需要记住的一点是,使用compose
引入小的HTML片段比不干燥和内联代码的性能要低得多。在这个问题的具体示例中,我可能倾向于重复HTML,而不是使用compose
。如果我们引入了更大的HTML块w/compose
,那么这就更有意义了。你给出的答案是正确的,只是我刚才提到的警告。艾希礼同意。如果不知道代码运行的上下文,就无法判断性能是否会成为问题。我一开始总是使用DRY,除非我知道运行时环境需要最大的效率。然后,如果测试显示不可接受的性能,我将在必要时故意违反DRY以提高速度。我希望用一种不太“冗长”的方法来完成这项任务,而不需要拆分元素shell(按钮
或a
)&内容,因为内容只包含两个“无法生存”的元素独立的,因此不需要是一个独立的组件。我想这是可行的,尽管我不能解释为什么,但我还是希望尽可能明确地使用语义正确的标记。我会在技术上无法使用正确标记的情况下使用角色
(例如,自定义组合框
由div
或任何类似内容组成)。谢谢你的建议!