在我的应用程序中,我正在使用 knockout 。 我有一组问题,每个问题都有一个类型,它决定了将在其中呈现问题的组件(问题模板,请参见下文)。
我的问题是它将所有 if 语句渲染到页面中。所以我的页面充满了 if 语句(这使得 html 页面变大),它们是空的。
HTML 示例:
<div data-bind="template: {name: 'questions', foreach: questions }">
<!-- ko if: type === "label" -->
<!-- ko template: { name: 'label_component' } -->
<div data-bind="visible: show, css: { root : isRoot }" class="root">
<div data-bind="html: text, attr: {id: id}" id="1">Question text</div>
</div>
<!-- /ko -->
<!-- /ko -->
<!-- ko if: type === "bool" --><!-- /ko -->
<!-- ko if: type === "multitext" --><!-- /ko -->
<!-- ko if: type === "text" --><!-- /ko -->
<!-- ko if: type == "number" --><!-- /ko -->
<!-- ko if: type === "dropdown" --><!-- /ko -->
<!-- ko if: type === "date" --><!-- /ko -->
............
因此您可以看到为 1 个组件渲染了 7 个不必要的 if 语句。
我的模板:
<div data-bind="template: {name: 'questions', foreach: questions }"></div>
<script id="questions" type="html/text">
<!-- ko if: type === "label" -->
<!-- ko template: { name: 'label_component' } --><!-- /ko -->
<!-- /ko -->
<!-- ko if: type === "bool" -->
<!-- ko template: { name: 'radio_btn_component' } --><!-- /ko -->
<!-- /ko -->
<!-- ko if: type === "multitext" -->
<!-- ko template: { name: 'multi_text_component' } --><!-- /ko -->
<!-- /ko -->
<!-- ko if: type === "text" -->
<!-- ko template: { name: 'text_component' } --><!-- /ko -->
<!-- /ko -->
<!-- ko if: type == "number" -->
<!-- ko template: { name: 'numeric_component' } --><!-- /ko -->
<!-- /ko -->
<!-- ko if: type === "dropdown" -->
<!-- ko template: { name: 'dropdown_component' } --><!-- /ko -->
<!-- /ko -->
<!-- ko if: type === "date" -->
<!-- ko template: { name: 'date_component' } --><!-- /ko -->
<!-- /ko -->
</script>
所以我的问题是: 有没有办法解决?我可以以某种方式停止将那些未使用的 if 语句渲染到页面中吗?
谢谢大家的想法
最佳答案
感谢@gkb,我从不同的 Angular 看待它并提出了这个解决方案。
<div data-bind="template: {name: 'questions', foreach: questions }"></div>
<script id="questions" type="html/text">
<!-- ko template: { name: componentName() } --><!-- /ko -->
</script>
而 componentName 是我的 View 模型上的一个函数:
question.componentName = function() {
switch (question.type) {
case "label":
return "label_component";
case "bool":
return "radio_btn_component";
case "multitext":
return "multi_text_component";
case "text":
return "text_component";
case "number":
return "numeric_component";
case "dropdown":
return "dropdown_component";
case "date":
return "date_component";
}
return "label_component";
}
如果您有任何其他想法如何实现这一目标。请告诉我。
关于javascript - knockout ,太多无容器 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41141636/