如何在使用组件时定义模板url

How to define a template url when using a component

本文关键字:定义 url 组件      更新时间:2023-09-26

我使用的是淘汰组件,但我想使用模板url而不是内联模板。这是我正在使用的组件:

ko.components.register('cat-data', {
    viewModel: {
        createViewModel: function(params, componentInfo) {
            var self = this;
            self.data = (params && params.data) || [];
            return self;
        }
    },
    template: "/Scripts/CatdDataTemplate.html"
});

当我运行此/Scripts/CatdDataTemplate.html时,会显示它,而不是实际的模板。

通过敲除将字符串形式的模板属性解析为要应用的实际模板。如果你想从url加载模板,你可以使用自定义加载程序来完成,如下面引用的淘汰文档中所定义的:

如果您的自定义加载器实现loadTemplate和/或loadViewModel,然后您可以将自定义代码插入到加载过程中。你也可以使用这些函数可以解释自定义配置格式。

例如,您可能希望启用配置格式,如以下内容:

ko.components.register('my-component', {
    template: { fromUrl: 'file.html', maxCacheAge: 1234 },
    viewModel: { viaLoader: '/path/myvm.js' } 
});

…并且您可以使用自定义加载程序来完成此操作。

以下自定义加载程序将负责加载模板使用fromUrl值配置:

var templateFromUrlLoader = {
    loadTemplate: function(name, templateConfig, callback) {
        if (templateConfig.fromUrl) {
            // Uses jQuery's ajax facility to load the markup from a file
            var fullUrl = '/templates/' + templateConfig.fromUrl + '?cacheAge=' + templateConfig.maxCacheAge;
            $.get(fullUrl, function(markupString) {
                // We need an array of DOM nodes, not a string.
                // We can use the default loader to convert to the
                // required format.
                ko.components.defaultLoader.loadTemplate(name, markupString, callback);
            });
        } else {
            // Unrecognized config format. Let another loader handle it.
            callback(null);
        }
    } };   // Register it ko.components.loaders.unshift(templateFromUrlLoader);

来源:http://knockoutjs.com/documentation/component-loaders.html#example-2-组件加载-加载-外部文件-自定义代码