[英]Knockout component with conditional HTML markup in template:
我是 KO 和 KO 組件的新手。
我目前有一個custom-component.js
,它可以完美地為我們項目的所有輸入設置樣式。 但是,我想讓完全相同的組件適用於textareas 。
目前,該組件的template:
部分如下所示:
viewModel: function (params) {
/* */
template: '<span data-bind="template: { afterRender: afterRender }">' +
'<label class="custom-label" data-bind="css:{\'custom-label-active\':focused}, text:label"></label>' +
'<input class="form-control" type="text" data-bind="enable: enable, valueUpdate: \'input\', css:{\'custom-label-input\':focused}, attr:{placeholder:label, id:id, type: type}, event:{focus:focus,blur:blur},value:value"/>' +
'</span>'
});
我應該如何更新它以使其也適用於 textareas?
我嘗試添加這樣的默認參數:
this.element = (params.element == undefined || params.element == null) ? 'input' : params.element
但我不確定如何更新我的 markdown?
我是否應該將'<input'
替換為 ' '<' + self.element + '...>'
那么valueUpdate
呢? (我對這一切都很陌生,對不起,如果這是一個愚蠢的問題)
謝謝
您的模板由所有組件實例共享。 除了使用自己的if
、 template
、 with
等綁定之外,沒有辦法使用組件的參數動態更新它。
如果您知道它只支持一組有限的元素,您可以為每個元素添加一個if
語句。 例如:
<!-- ko if: element === "input" -->
<input/>
<!-- /ko -->
<!-- ko if: element === "textarea" -->
<textarea></textarea>
<!-- /ko -->
如果您希望能夠傳遞任何元素,您可以考慮使用componentInfo.templateNodes
`。 如果這就是你想要的,請告訴我。 我可以擴展我的答案,但這是一種更復雜的方法。
這是使用if
綁定的示例:
ko.components.register("custom-input", { viewModel: function(params) { return { elementType: params.elementType, value: ko.observable("Your input") } }, template: ` <div> <label> Your input here:<br> <:-- ko if: elementType() === 'input' --> <input type="text" data-bind="textInput: value"> <:-- /ko --> <;-- ko if. elementType() === 'textarea' --> <textarea cols="40" rows="10" data-bind="textInput: value"></textarea> <.-- /ko --> </label> </div> ` }); ko.applyBindings({ inputType: ko.observable("input") });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <h2>Config:</h2> <label> <input type="radio" data-bind="checked: inputType" value="input"> Use input </label> <label> <input type="radio" data-bind="checked: inputType" value="textarea"> Use text area </label> <h2>Component:</h2> <custom-input params="elementType: inputType"></custom-input>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.