首页 > 解决方案 > 创建淘汰组件时运行外部函数

问题描述

我正在尝试在淘汰赛中创建新组件:

ko.components.register("categories", {
    viewModel: {
        instance: MY_VIEW_MODEL
    },
    template: require('html-loader?interpolate!./components/categories.html')
});

和categories.html内的我的 HTML 块:

<div class="panel" data-bind="foreach: categories, afterRender: ${require('../effects.js').fadePanels()}"></div>

effect.js内部:

function fadePanels() {
    $('.panel').velocity('fadeInPanels', {
        stagger: 250,
    })
}

加上webpack.config.js

    test: /\.html$/,
    loader: 'html-loader',
    options: {
        interpolate: true
    },
    exclude: /node_modules/

但它根本不起作用。这是浏览器的输出(控制台中没有错误): 在此处输入图像描述

你有这方面的经验吗?你知道如何正确处理吗?

标签: webpackknockout.jswebpack-html-loader

解决方案


createViewmodel您可以使用工厂方法运行一个获取组件元素的函数。此函数接收一个包含当前element.

ko.components.register("category", {
    viewModel: { 
      createViewModel: (params, info) => {
        fadeIn(info.element);
        return { label: "hello world" }
      } 
    },
    template: `<div data-bind="text: label"></div>`
});

const categories = ko.observableArray(["", "", ""]);
const addCat = () => categories.push("");

ko.applyBindings({ categories, addCat  });

function fadeIn(el) {
  el.classList.add("seeThrough");
  setTimeout(
    () => el.classList.add("fadeIn"), 
    200
  );
}
.seeThrough {
  opacity: 0;
  transition: opacity .25s ease-in-out;
}

.fadeIn {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: categories">
  <li data-bind="component: { name: 'category' }"></li>
</ul>

<button data-bind="click: addCat">add</button>

对于使用组件和 webpack,您可能想查看我几天前写的这个答案。它描述了如何配置 webpack 以使用淘汰组件。


推荐阅读