我有一些 alpinejs 的嵌套自定义选择菜单:
<template x-for="(attribute, rootindex) in attributes">
<div x-ref="attribute.name"
x-data="{open: false, selectedIndex: false, activeIndex: null, selectedItem:false, items:[...], placeholder:'Choose '+attribute.label }"
class="my-5">
...
您可以看到每个子项都有自己的状态/变量,例如 open、selectedIndex、selectedItem,... 在某些情况下我想设置其中一些状态:
我尝试在 child 身上使用外部引用,但它不起作用,并且会返回未定义! 该函数位于父级:
deleteAttribute(index) {
for (let i = index; i < this.attributes.length; i++) {
delete this.selected[this.attributes[i].name];
this.$refs[this.attributes[i].name].selectedItem = false;
}
您能告诉我如何访问子状态吗? 例如,我想在特定子项中将某些“selectedItem”设置为 false
提前非常感谢
最佳答案
您可以使用 Alpine.$data(element) api
<head>
<script src="https://unpkg.com/alpinejs" defer></script>
<script>
let data = {
attrs: [{
key: 'no1',
name: 'first'
},
{
key: 'no2',
name: 'second'
},
{
key: 'no3',
name: 'third'
}
],
toggle(index) {
let el = document.getElementById(`child-${index}`)
let data = Alpine.$data(el)
data.selected = !data.selected
}
}
</script>
</head>
<body x-data="data">
<template x-for="(attr, index) of attrs">
<div x-data="{selected: false}">
<p :id='`child-${index}`' x-text="attr.name + (selected ? '[x]' : '[-]')"></p><button @click="toggle(index)">Toggle </button>
</div>
</template>
</body>
关于javascript - Alpinejs : change values inside children from parent element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73899144/