我创建了一个淘汰模板.... 如何从此模板中获取foreach的关键和值...
<!-- ko foreach: { data: getCouponCodes(), as: 'key => value' } -->
我需要获得关键和价值
答案 0 :(得分:0)
如果getCouponCodes
返回一个对象数组,那么就没有&#34;特殊&#34;敲除直接在绑定中获取这些对象的键和值的方法。
换句话说:您必须在视图或视图模型中使用纯JavaScript。有许多可能的解决方案,这里有两个解决方案:
computed
将数据转换为所需格式:
const getCouponCodes = () => [ { name: "John" }, { name: "Kevin" } ]
ko.applyBindings({
couponData: ko.pureComputed(() =>
// Use whatever logic you require to return a viewmodel of "key" and "value"
getCouponCodes()
.reduce(
// You can also use: `for ... in`, `Object.keys`, etc.
// search for "Iterate over js object" to learn more
(data, coupon) => data.concat(Object.entries(coupon)),
[]
)
// Here we construct a simple viewmodel to make our data-binds easier
.map(([k, v]) => ({ key: k, value: v }))
)
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: couponData -->
<div data-bind="text: key + ': ' + value"></div>
<!-- /ko -->
&#13;
Object.keys
和$parent
ko.applyBindings({
getCouponCodes: () => [ { name: "John" }, { name: "Kevin" } ]
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: getCouponCodes() -->
<!-- ko foreach: Object.keys($data) -->
<div data-bind="text: $data + ': ' + $parent[$data]"></div>
<!-- /ko -->
<!-- /ko -->
&#13;