简体   繁体   English

有没有办法使用 Alpine.js 向循环对象添加属性或组件数据?

[英]Is there a way to add properties or component data to looped objects with Alpine.js?

Essentially I'm receiving JSON from the server and would like to add properties to the objects I'm looping or the x-data of the component, is this possible with alpine.js?本质上,我从服务器接收 JSON 并想向我正在循环的对象或组件的x-data添加属性,这可能与 alpine.js 一起使用吗?

The data is something that will be requested on an interval and looks something like:数据是按时间间隔请求的,类似于:

let teams = [
    { id: 1, name: 'Person 1'},
    { id: 2, name: 'Person 2'},
    ...
];

What I'd like to do is add a new property favourite to the looped team object, with default set to false or add it as component data.我想要做的是向循环的team对象添加一个新的属性favourite ,默认设置为false或将其添加为组件数据。 I plan to use this property to filter the list later on.我计划稍后使用此属性来过滤列表。 At the moment I have:目前我有:

<template x-for="team in teams" :key="team.id">
    <tr>
        <td x-text="team.name"></td>
        <td>
            <input type="checkbox" x-model="favourite">
        </td>
    </tr>
</template>

I have tried a few things to get this working, such as using:我尝试了一些方法来使其正常工作,例如使用:

x-data="{ team: team, favourite: false }"

On both the tr and template tag as well as without passing the team object to the x-data directive.trtemplate标签上,以及不将team对象传递给x-data指令。 It seems like there is a clash between the x-for and x-data directives as this throws an error: Uncaught ReferenceError: team is not defined x-forx-data指令之间似乎存在冲突,因为这会引发错误: Uncaught ReferenceError: team is not defined

I have also tried using x-init alongside the x-data directive to no avail.我还尝试将x-initx-data指令一起使用,但无济于事。

At this stage I'm wondering if I'll have to switch to another JS library to get this working (recommendations welcome if necessary) or if my approach is fundamentally wrong.在这个阶段,我想知道是否必须切换到另一个 JS 库才能使其正常工作(如有必要,欢迎提出建议),或者我的方法是否从根本上是错误的。

Any help/pointers would be much appreciated.任何帮助/指针将不胜感激。

In principle what you should be doing is adding the "favourite" field before it gets to the x-for .原则上你应该做的是在它到达x-for之前添加“收藏夹”字段。

For example if you're loading teams using fetch you could do:例如,如果您使用fetch加载teams您可以执行以下操作:

<div
  x-data="{ teams: [] }"
  x-init="setInterval(() => {
    fetch('/teams-url').then(res => res.json()).then(teamsData => {
      teams = teamsData.map(team => ({ favourite: false, ...team }));
    });
  }, 1000);"
>

I also noticed that your example is using v-model and v-text , which should be x-model and x-text respectively.我还注意到您的示例使用的是v-modelv-text ,它们应该分别是x-modelx-text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM