Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

V-for with simple arrays: what key to use?

Tags:

vue.js

I’d like to know how people use v-for with such simple arrays. I think these are the options I have. The first option means there’s no place for simple arrays.

Use arrays of objects instead, explicitly declaring a key for each item. Don’t use a key in the v-for.

How to display one element from an array?

 `<template>:`

    <ul>
        <li v-for="fruit in fruits" :key="fruit"></li>
    </ul>

<script>:

export default {
        data() {
            return {
                fruits: ['apple', 'banana', 'orange']
            };
        }
    };
like image 305
Лена Фролова Avatar asked Oct 24 '25 14:10

Лена Фролова


1 Answers

First of all, don't put ; symbols in your script there. Just use commas , to separate data, methods, computed, etc.

  • You don't have to specify a key if you are not going to use it.

  • To display elements in the loop, you just put it in double curly braces {{ }}.

  • If you will need an index, you can specify it after the item. To display it, you do the same thing, just put it in double curly braces: {{index}}

Codepen: https://codepen.io/x84733/pen/dKwjBL?editors=1010

<ul>
  <li v-for="(fruit, index) in fruits">
    {{index}}: {{fruit}}
  </li>
</ul>

...

data () {
  return {
    fruits: ['apple', 'banana', 'orange'] 
  }
},
methods: {
  ...
}
like image 184
Un1 Avatar answered Oct 26 '25 03:10

Un1