gpt4 book ai didi

javascript - 了解嵌套组件绑定(bind)如何在 KnockoutJS 上工作

转载 作者:行者123 更新时间:2023-11-30 00:14:26 25 4
gpt4 key购买 nike

我正在尝试使用 knockout 组件,我正在尝试使用的一件事是嵌套组件,如下所示:

<parent-component params="parentText: parentText">
<child-component params="childText: childText"></child-component>
</parent-component>

parentText 和 childText 都是同一 View 模型对象的成员,但是当我运行它时出现以下错误:

未捕获的 ReferenceError:无法处理绑定(bind)“template: function (){return { nodes:$componentTemplateNodes} }”消息:未定义 childText

这是我尝试运行的示例:

var ParentComponent = function(params) {
var self = this;
self.parentText = params.parentText;
};

ko.components.register('parent-component', {
viewModel: ParentComponent,
template: '<div><p><strong data-bind="text: parentText"></strong></p><!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko --></div>'
})

var ChildComponent = function(params) {
var self = this;
self.childText = params.text2;
};

ko.components.register('child-component', {
viewModel: ChildComponent,
template: '<p data-bind="text: childText"></p>'
})

var ViewModel = function() {
var self = this;
self.title = 'KnockoutJS component test';
self.parentText = 'This is the text1';
self.childText = 'This is the text2';
};

ko.applyBindings(new ViewModel(), document.getElementById('content'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="content">
<h1 data-bind="text: title"></h1>
<parent-component params="parentText: parentText">
<child-component params="childText: childText"></child-component>
</parent-component>
</div>

任何人都可以向我解释我做错了什么吗?

谢谢,

最佳答案

你做得很好。不过,我可以在这里看到 2 个问题。

首先:

$componentTemplateNodes在这种情况下看不到,因为您使用的是尚不支持的 knockout 3.2,所以您最好将 lib 更新到较新的库,knockout 3.4 已经出来了,但是 $componentTemplateNodes支持从 3.3 开始。

第二:

在您的 ChildComponent 虚拟机中,您引用了参数 text2

self.childText = params.text2;

但是当您在 html 绑定(bind)中声明它时,它的名称为 childText .

<child-component params="childText: childText"></child-component>

还要注意 <child-component params="childText: childText"></child-component>被封装在一个内部组件中,所以 childText在这里看不到,所以你应该把它称为$root.childText .

总结一下:绑定(bind)应该是。

<parent-component params="parentText: parentText">
<child-component params="childText: $root.childText"></child-component>
</parent-component>

ChildComponent 虚拟机应该是:

self.childText = params.childText;

关于javascript - 了解嵌套组件绑定(bind)如何在 KnockoutJS 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35248508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com