Create New Post

Vue.js List Rendering

List rendering in Vue.js involves rendering a list of items dynamically based on an array or an object. Vue.js provides several directives to handle list rendering. Here are some common techniques for list rendering in Vue.js:

  1. v-for Directive: The v-for directive is used to iterate over an array and render elements for each item in the array.

    <template>
    <ul>
    <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
    </template>

    <script>
    export default {
    data() {
    return {
    items: [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
    { id: 3, name: 'Item 3' }
    ]
    };
    }
    };
    </script>

    The :key attribute is essential when using v-for to help Vue.js efficiently update the DOM.

  2. v-for with Index: You can also access the index of the current iteration using v-for.

    <template>
    <ul>
    <li v-for="(item, index) in items" :key="index">{{ index + 1 }}. {{ item.name }}</li>
    </ul>
    </template>

    <script>
    export default {
    data() {
    return {
    items: [
    { name: 'Item 1' },
    { name: 'Item 2' },
    { name: 'Item 3' }
    ]
    };
    }
    };
    </script>

  3. Rendering an Object with v-for: You can use v-for to iterate over the properties of an object.

    <template>
    <ul>
    <li v-for="(value, key) in user" :key="key">{{ key }}: {{ value }}</li>
    </ul>
    </template>

    <script>
    export default {
    data() {
    return {
    user: {
    name: 'John Doe',
    age: 25,
    email: '[email protected]'
    }
    };
    }
    };
    </script>

  4. v-for with v-if: You can combine v-for with v-if to conditionally render items.

    <template>
    <ul>
    <li v-for="item in items" :key="item.id" v-if="item.status === 'active'">
    {{ item.name }}
    </li>
    </ul>
    </template>

    <script>
    export default {
    data() {
    return {
    items: [
    { id: 1, name: 'Item 1', status: 'active' },
    { id: 2, name: 'Item 2', status: 'inactive' },
    { id: 3, name: 'Item 3', status: 'active' }
    ]
    };
    }
    };
    </script>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

38090