我有一个用户列表,并按标题对他们进行了排序。创建列表时,我想检查前一个用户的标题是否与当前用户不同,如果是,则执行一些逻辑。
<div>
<div v-for="user in the_category`.`users" :key="user.id">
<h1 v-bind:title="user.title" >{{ user.title }}</h1>
// If the title is not the same as the previous user.title I would like the following <h3> below to show
// However if the title is the same as the previous user.title I do not want it to show.
// How do I pass the value/text of the <h1> to my title data variable
// and compare the value with the last value on each loop?
<h3 v-show="user.title != title">This is a new title</h3>
</div>
</div>
</template>
<script>
export default {
props: [
"the_category",
"title"
],
data: function() {
return {
category: this.the_category,
title: "",
};
},
}
</script>
```
最佳答案
您可以在 v-for
中获取循环索引然后用它来检查整个数组。
首先,替换这个:
v-for="user in the_category`.`users"
有了这个:
v-for="(user, index) in the_category`.`users"
这将同时获取当前元素 ( user
) 及其在数组中的索引 ( index
)。
然后,替换为:
<h3 v-show="user.title != title">This is a new title</h3>
有了这个:
<h3 v-show="index === 0 || user.title != the_category`.`users[index - 1].title">This is a new title</h3>
你的 <h3>
如果您的元素是第一个 ( index === 0
) 或者如果当前标题与之前的不同,那么将是可见的。
关于javascript - 如何在 for 循环的每次迭代中将值从 HTML 标记传递到 Vue 的数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58307711/