Vue.js 3.0 Tutorial

Vue.js 3.0 Component Advanced

Vue.js 3.0 Transitions & Animations

Vue.js 3.0 Reusable & Combinable

Vue.js 3.0 Advanced

Vue.js 3.0 Tools

Vue.js 3.0 Scale

Vue.js 3.0 Accessibility

Vue.js 3.0 Migrating from Vue2

Vue.js 3.0 Contribute Documentation

Vue.js 3.0 API References

Vue.js 3.0 Style Guide

Vue 3.0 key attribute

The key attribute in Vue is a special attribute primarily used in the context of the v-for directive, but it can be useful in other scenarios as well, such as in managing transitions or component re-renders. Its main function is to help Vue track each node's identity, and it greatly improves Vue's reactivity system by helping Vue determine which items have been added, removed, or changed in the array.

Here's a simple tutorial to show how the key attribute is used:

Step 1: Initialize your Vue project.

Create a new Vue 3 project using the Vue CLI.

vue create my-project

Remember to choose Vue 3 when asked which version of Vue to use.

Step 2: In your App.vue file (or any other component where you want to render a list), add a v-for directive to render an array of items, and use the key attribute to give each item a unique identifier.

Here's an example:

<template>
  <div>
    <h1>Task List</h1>
    <ul>
      <li v-for="task in tasks" :key="task.id">
        {{ task.name }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tasks: [
        { id: 1, name: 'Do laundry' },
        { id: 2, name: 'Buy groceries' },
        { id: 3, name: 'Clean room' },
      ],
    };
  },
};
</script>

In this example, we use the v-for directive to loop over an array of tasks and render each one as an li element. We use the :key attribute (shorthand for v-bind:key) to bind each task's unique id as its key.

Step 3: Run your application.

You can run your Vue 3 application with the following command:

npm run serve

You should now see the task list rendered in your browser. If you inspect the li elements in your browser's dev tools, you won't see the key attribute, but Vue uses it internally to track each element.

Remember that every element in a v-for loop should have a unique key value. This helps Vue to accurately track and rerender elements whenever data changes. The value of key should be unique among its sibling nodes. Reusing the same key for multiple elements can lead to rendering errors.

  1. Vue 3.0 v-bind:key Directive:

    • Description: The v-bind:key directive binds a dynamic value as the key attribute in Vue 3.0, crucial for efficient rendering of lists.
    • Code Example:
      <template>
        <div v-for="item in items" :key="item.id">{{ item.name }}</div>
      </template>
      
      <script>
      export default {
        data() {
          return {
            items: [
              { id: 1, name: 'Item 1' },
              { id: 2, name: 'Item 2' },
              // ...
            ],
          };
        },
      };
      </script>