简体   繁体   English

从 Vue.js 中的数组获取索引

[英]Getting index from Array in Vue.js

I'm trying to remove an entry in my array "joke" by clicking on the removeButton right next to the entry of the list.我试图通过单击列表条目旁边的 removeButton 来删除我的数组“笑话”中的一个条目。 I think it should be possible, that if i can somehow pass the id from the entry (in which the removeButton was clicked) to my remove function then this would solve my problem, but how?我认为这应该是可能的,如果我能以某种方式将条目中的 id(单击 removeButton 的位置)传递给我的 remove function 那么这将解决我的问题,但是如何解决?

the code:编码:

  <div>
    <ul>
      <li v-for="jokes in joke" :key="jokes.title" class="joke">
        <p class="title">{{ jokes.title }}</p>
        <p>{{ jokes.text }} (Id:{{ jokes.id }})</p>
        <v-btn icon @click="remove" id="removeButton><v-icon>mdi-sticker-remove-outline</v-icon></v-btn>
      </li>
    </ul>
  </div>

<script>
export default {
  name: "Liste",
  props: ["joke"],
  data: function() {
    return {

    };
  },

  methods: {
    remove: function() {
      this.$emit("removeEntry", {
       //here i want to pass the right id
      });
    },
  },
};
</script>

this is how the joke Array looks:这就是笑话 Array 的样子:

[{"id":"1","title":"title1","text":"a joke","rating":"4"},
{"id":"2","title":"title2","text":"funny joke","rating":"5"},
{"id":"3","title":"title3","text":"Nanother funny joke","rating":"2"}]

So for example i want to delete the Joke with the id="2",then i would click on the removeButton which is placed next to the joke entry in the List and i want to get the id 2 if the removeButton next to the entry was clicked to delete the entry from my Json array(i implemented this function in a other component, so here my only problem is to get the right id).因此,例如,我想删除 id="2" 的笑话,然后我会单击列表中笑话条目旁边的 removeButton,如果条目旁边的 removeButton ,我想获取 id 2单击以从我的 Json 数组中删除条目(我在其他组件中实现了这个 function,所以这里我唯一的问题是获得正确的 id)。

I hope i could discribe my problem clearly, if not feel free to ask me:) Thank you Guy in advance:), lof you <3我希望我能清楚地描述我的问题,如果不能随时问我:) 提前谢谢你 :),你 <3

In the remove button pass the joke id like:在删除按钮中传递笑话 id,如:

<v-btn icon @click="remove(jokes.id)"

and then update the method like:然后更新方法,如:

methods: {
  remove: function(id) {
    this.$emit("removeEntry", {
      id: id
    });
  },
},

Or, you can pass the id directly also:或者,您也可以直接传递 id:

methods: {
  remove: function(id) {
    this.$emit("removeEntry", id);
  },
},

Everyting goes fine.一切顺利。 Simple thing you should add, is an argument to your removeButton function.您应该添加的简单内容是您的removeButton function 的参数。

Here how it might look like:这里看起来可能是这样的:

removeButton(id){
   this.jokes.splice(id, 1);
}

And then in your template pass jokes.id as an argument然后在你的模板中传递jokes.id作为参数

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

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