javascript - 如何在 for 循环的每次迭代中将值从 HTML 标记传递到 Vue 的数据对象

标签 javascript vue.js

我有一个用户列表,并按标题对他们进行了排序。创建列表时,我想检查前一个用户的标题是否与当前用户不同,如果是,则执行一些逻辑。

      <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/

相关文章:

javascript - 在 JavaScript 中将用户输入元素输入到数组中

JavaScript 移动延迟和多次击键

javascript - 沿 SVG 路径动画 SVG 渐变

javascript - 如何在VueJS中动态更改点击事件

vue.js - 如何将收到的数据提交到Vue store?

javascript - Vuetify 日期选择器显示时没有事件图标且带有空白字段

javascript - Bootstrap-Vue : @click. native 在 <b-form-checkbox> 上表现得很奇怪

javascript - 如何将制表数据导出到 csv(包括格式)

javascript - 从标签中选择并用作属性 - vuejs

javascript - 搜索一个相关的json数据