Ask Your Question
1

How can the item self reference be used in Vue functions?

asked 2021-11-24 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-08-02 10:00:00 +0000

plato gravatar image

In Vue, the item self-reference can be used in many different ways to perform various operations on an item in a list. Here are a few examples:

  1. Updating a property of the item:
<template>
  <div v-for="(item, index) in items" :key="index">
    <input type="text" v-model="item.name">
  </div>
</template>

In this example, we have a list of items and we want to allow the user to update the name of each item. We use v-model to bind the name property of the current item to the text input, so that any changes made by the user will be reflected in the data.

  1. Deleting an item from the list:
<template>
  <div v-for="(item, index) in items" :key="index">
    <button @click="deleteItem(item)">Delete</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' },
      ],
    };
  },
  methods: {
    deleteItem(item) {
      const index = this.items.indexOf(item);
      this.items.splice(index, 1);
    },
  },
};
</script>

In this example, we have a list of items and a button for each item that, when clicked, should delete that item from the list. We use the deleteItem method to remove the item from the items array by finding its index and using splice to remove it.

  1. Filtering the list based on a property of the item:
<template>
  <div v-for="(item, index) in filteredItems" :key="index">
    <p>{{ item.name }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1', category: 'A' },
        { id: 2, name: 'Item 2', category: 'B' },
        { id: 3, name: 'Item 3', category: 'A' },
      ],
      filterCategory: 'A',
    };
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => item.category === this.filterCategory);
    },
  },
};
</script>

In this example, we have a list of items and we want to display only the items that belong to a certain category. We use a computed property filteredItems to filter the items array based on the category property of each item. The filterCategory value can be updated to change which items are shown.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-24 11:00:00 +0000

Seen: 1 times

Last updated: Aug 02 '22