【问题标题】:How to get array index from html element?如何从 html 元素中获取数组索引?
【发布时间】:2022-01-12 08:45:02
【问题描述】:

嘿,在我的 Vue 应用程序中,我有机会创建几个人:

<div v-for="newContent in temp" :key="newContent.id" @click="showId(newContent.id)"  v-show="true">

        <!-- Head of part personal data -->
        <h4 class="person" style="margin-left: 0.95vw">Person 1</h4>

        <!-- Enter Person Data -->
        <testmodul1></testmodul1>      

        <div class="trash">
          <button class="btn btn-outline-danger" @click="deletePerson()">Person löschen</button>
        </div>
        <hr />
</div>

如果我想添加更多人,有一个按钮,可以附加更多这样的人输入:

<button class="btn btn-outline-secondary" @click="useIt()">Add more persons</button>

useIt(){
  this.temp.push({
    id:this.id+=1
  })
  console.log(this.temp);
},

data() {
return {
  id:0,
  temp:[{
    id:0,
  }]
};

},

控制台中console.log方法的输出(点击添加按钮2次):

Proxy {0: {…}, 1: {…}, 2: {…}}
[[Handler]]: Object
[[Target]]: Array(2)
0: {id: 0}
1: {id: 0}
length: 2
[[Prototype]]: Array(0)

现在有以下问题:假设我们创建了 3 个新人。现在我认识到,第二个人是假的,我想删除它。当我单击 person 2 时,我想获取 html 元素的数组索引。我已经尝试过了,但效果并不好:

<div v-for="newContent in temp" :key="newContent.id" @click="showId(newContent.id)"  v-show="true">

showId(index){
  alert(index);
  }

还有其他方法可以找出我点击的 html div 数组中的索引吗?

【问题讨论】:

  • “效果不佳”到底是什么意思?什么是警报?

标签: javascript html vue.js


【解决方案1】:

请检查Vue.js list rendering

你可以像这样遍历包含元素和索引的数组:

<li v-for="(item, index) in items">
    {{ index }} - {{ item.message }}
</li>

对于您的情况:

<div v-for="(newContent, index) in temp" :key="newContent.id" @click="showId(index)" v-show="true">

【讨论】:

    【解决方案2】:

    您可以在 v-for 循环本身中定义索引变量。喜欢

    <div v-for="(person,index) in persons" :key="index">
        {{index}} //which is index of current item
    </div> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2020-06-30
      • 2022-08-16
      相关资源
      最近更新 更多