webpack - 创建淘汰组件时运行外部函数
问题描述
我正在尝试在淘汰赛中创建新组件:
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/
你有这方面的经验吗?你知道如何正确处理吗?
解决方案
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 以使用淘汰组件。