如何解决x-for 在带有变量引用的 Alpine.js 中不起作用
这是我的 Html 代码,它用于显示帖子列表。单击一行时,在该帖子中显示一个包含消息的对话框。
<div class="container">
<div class="panel panel-default" x-data="posts()">
<div class="panel-heading">Bubbles</div>
<ul class="list-group">
<template x-for="(post,index) in posts" x-item="index">
<li class="list-group-item">
<div style="display: flex; justify-content: space-between;">
<span x-text="post.title"></span>
<button class="btn btn-primary" @click="onCooperationBtnClick($event,post)">Cooperate</button>
</div>
</li>
</template>
</ul>
<div class="modal fade" tabindex="-1" role="dialog" id="dialog" data-backdrop="static" data-keybord="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title">Dialog</h4>
</div>
<div class="modal-body">
<template x-if="currentPost" x-for="(message,index) in currentPost.messages" x-item="index">
<div>
<span x-text="message.content"></span>
</div>
</template>
</div>
<div class="modal-footer">
<div class="input-group">
<input type="text" class="form-control" x-model="message" maxlength="50" placeholder="say something">
<div class="input-group-btn">
<button class="btn" x-bind:disabled="!message">send</button>
</div>
</div>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>
我的js代码:
function posts() {
return {
posts: [
{
"id": 2,"title": "BBBBBBBBBBBBB","messages": [
{
"id": 2,"content": "123123123123",},{
"id": 3,}
]
},{
"id": 1,"title": "AAAAAAAAAA","messages": [
{
"id": 1,}
]
}
],currentPost: null,dialogOpen: false,message: '',onCooperationBtnClick($event,post) {
this.currentPost = post
$('#dialog').modal('show')
}
}
}
它应该在span中显示消息内容,但没有。将 message.content
更改为 index
值,它起作用了,并且消息数匹配。
更奇怪的是,当我把 <button @click="console.log(currentPost.messages[0].content)"></button>
放在里面时,它打印出正确的东西!
那么,有什么问题吗?
解决方法
所以看起来你在这里混合了 jQuery 和 AlpineJs。可能发生的是 jQuery 在 DOM 中更新 Alpine 的反应性属性之前显示模态。在 Alpine 的响应式道具更新后,您需要使用 Alpine 的 $nextTick
方法来显示模态:
onCooperationBtnClick($event,post) {
this.currentPost = post
this.$nextTick(() => {
$('#dialog').modal('show')
})
}
理想情况下,您应该在此处删除 jQuery,只需切换使用 Alpine 显示模态所需的相关类。