![](/img/trans.png)
[英]Is there a way to add properties or component data to looped objects with Alpine.js?
[英]Cloning HTML element with Alpine.js component
我有 Html 元素和 Alpine.js 组件。 我希望能够克隆它(使用 jQuery)。 不幸的是,它不起作用——当我使用x-for
时,我得到:
ReferenceError:未定义选项
实际上有些元素内容是重复的(每个段落显示两次“一二三”)
显然这里的代码是简化的(事实上我想用更多的组件方法克隆自定义下拉菜单)但我相信简化的代码清楚地显示了问题。
Html 代码:
<div>
<p x-data="{...CustomComponent}" x-init="initialize()">
<template x-for="option in options">
<span x-text="option"></span>
</template>
</p>
</div>
<button>Clone element</button>
JavaScript 代码:
const CustomComponent = (function() {
return {
options: [],
initialize()
{
this.options = ['one', 'two', 'three'];
}
}
}());
$('button').on('click', function() {
$('div').append($('p').first().clone());
});
似乎解决方案是拥有在克隆之前不会被解析的元素副本:
Html:
<div>
<p x-data="{...CustomComponent}" x-init="initialize()">
<template x-for="option in options">
<span x-text="option"></span>
</template>
</p>
</div>
<button>Clone element</button>
<template class="tpl">
<p x-data="{...CustomComponent}" x-init="initialize()">
<template x-for="option in options">
<span x-text="option"></span>
</template>
</p>
</template>
JavaScript:
const CustomComponent = (function() {
return {
options: [],
initialize()
{
this.options = ['one', 'two', 'three'];
}
}
}());
$('button').on('click', function() {
$('div').append($('template.tpl').html());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.