首页 > 解决方案 > 淘汰 if 和文本绑定

问题描述

我正在尝试在 Knockout (3.3.0) 中创建一个简单的组件:

ko.components.register('test', {
    viewModel: function() {
        this.test = 'hello'
    },
    template:
        `<span data-bind='if: 1, text: test'></span>`
});
ko.applyBindings();

小提琴

<test></test>现在,当我在其他地方实例化 a 时,出现错误:

Multiple bindings (if and text) are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.

这真的不可能吗?如果您问我,这就像要合并的最基本功能。我知道我可以使用<!-- ko text -->,但是如何设置其他属性,比如src同时使用if呢?

标签: javascriptknockout.jsknockout-components

解决方案


好的,我找到了(或至少是一种可能的)解决方案:使用<!-- ko if --><!-- /ko -->. 这样,模板可以写成

<!-- ko if: 1-->
<span data-bind='text: test'></span>
<!-- /ko -->

我仍然不认为它是完美的,在 Vue 中我会做得<span v-if='1'>{{text}}</span>很好,但我想这个世界上并不是所有东西都能像 Vue 一样棒......


推荐阅读