我更改了先前的示例代码和逻辑。我需要单击按钮,然后按元素ID折叠from div。折叠文字来自KO 数组,如果数组存在,我希望按钮可见。数据绑定“可见:存在Array1..2”
<div class=«header»>
<!— ko if: typeof Array1 !== 'undefined' —>
<button data-toggle="collapse" href="#containerLoan<?= $key + 1 ?>» aria-expanded=" false" aria-controls="containerLoan<?= $key ? >">button1</button>
<!-- /ko -->
<!— ko if: typeof Array2 !== 'undefined' —>
<button data-toggle="collapse" href="#containerLoan<?= $key + 2 ?>»
aria-expanded=" false
" aria-controls="containerLoan<?= $key ?>">button2</button>
<!-- /ko -->
</div>
<div class=«loandata» data-bind='component: { name: «test-component", params: { Id: <?= $model->Id ?>} }'></div>
<script type="text/html" id=«test-template">
<div class="collapse multi-collapse" id="containerLoan<?= $key + 1 ?>">
<div class="card card-body">
<!-- ko if: Array1.length > 0 -->
<div>…</div>
<!-- /ko -->
</div>
</div>
<div class="collapse multi-collapse" id="containerLoan<?= $key + 2 ?>">
<div class="card card-body">
<!-- ko if: Array2.length > 0 -->
<div>…</div>
<!-- /ko -->
</div>
</div>
</script>
在* .ts中 命名空间Test.One {
export class TestViewModel {
…
Array1: KnockoutObservable<Product> = ko.computed(() => { … return …; }
Array2: KnockoutObservable<Product> = ko.computed(() => { … return …; }
private fetch(id: number): void {
$.getJSON(…)
}
constructor(params: { Id: number }) {
this.Id(params.Id);
this.fetch(params.Id);
}
export class ViewModel {
constructor() {
ko.components.register(‘test-component', {
viewModel: params => {
return new TestViewModel(params);
},
template:{
element :
'hint-loan-product-template'
},
});
}
}
export let viewModelObject = new ViewModel();
ko.cleanNode(document.getElementById(‘test-area’));
ko.applyBindings(viewModelObject);//, document.getElementById(‘test-area'));
}
答案 0 :(得分:1)
最好的解决方案是通过组件的isVisible
显式传递对params
的引用。这样,您就不会创建强制将组件仅在包含特定属性的绑定上下文中使用的硬依赖关系。
下面是一个示例,使用了the knockout docs
中的某些组件outerIsVisible
isVisible
,该视图模型引用了params
中的一个视图
ko.components.register('message-editor', {
viewModel: function(params) {
this.isVisible = params.isVisible;
this.text = ko.observable(params && params.initialText || '');
},
template: `<div data-bind="visible: isVisible">
Message: <input data-bind="textInput: text" />
(length: <span data-bind="text: text().length"></span>)
</div>`
});
ko.applyBindings({
outerIsVisible: ko.observable(true)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>
<input type="checkbox" data-bind="checked: outerIsVisible">
Show message editor
</label>
<div data-bind='component: {
name: "message-editor",
params: {
initialText: "Hello, world!",
isVisible: outerIsVisible
}
}'></div>