v-for

2022. 3. 14. 18:07Vue

1. v-for로 엘리먼트 배열에 매핑하기 

items는 원본 데이터 배열이고 item은 반복되는 배열 엘리먼트의 별칭 이다.

key에 대한 이상적인 값은 각 항목을 식별할 수 있는 고유한 ID이다. v-for를 쓴다면  :key 키값을 넣어주자!

>> 코지코더 강의 듣는데 :key값에 index 넣는걸 별로 추천하지 않는다고 한다.

왜냐하면 3번째 index값을 만약에 삭제하면 4번째가 3번째로 되기 때문에 key로 가지기가 애매하다고 하셨다.

<div v-for="(item, index) in items" :key="index">
 {{ index + 1}} : {{ item.fruit }}
</div>
data() {
  return {
    array: [
      { fruit: 'apple' },
      { fruit: 'banana' },
      { fruit: 'mango' }
    ]
  };
},

 

 

 

2. v-for와 객체

<div v-for="(value, key, index) in object" :key="value">
    {{ value }}, {{ key }}, {{ index }}
</div>
  data() {
    return {
      object: {
        title: '제목',
        menu: '메뉴',
        button: '버튼'
      }
    };
  },

 

 

 

3. 필터링 / 정렬 된 결과 표시하기

<li v-for="n in evenNumber" :key="n">{{ n }}</li>
data() {
  return {
    number : [1, 2, 3, 4, 5]
  };
},
computed: {
  evenNumber() {
    return this.number.filter(n => n % 2 === 0)
  }
},

복잡한 계산식이 있을 때는 methods 말고 copmuted 속성을 통해 미리 계산되어 있는 값을 반환하도록 배웠다지!

 

 

 

 

 

4. 경고 해결법

v-for을 사용할때 :key="todo"로 하니깐 정상 작동은 되지만 경고창이 떴다!

 <div v-for="todo in todos" :key="todo">
   {{ todo.title }}
 </div>

<div v-for="(todo, index) in todos" :key="index">
  {{ todo.title }}
</div>

구글링해서 찾아보니 key값은 문자열과 숫자만 되는것이다!! 나는 객체 타입으로 넣어줘서 error 난거였음

 

 

 

 

5. todoList

<form @submit.prevent="addNewTodo">
  <label for="new-todo">해야할 목록 : </label>
  <input type="text"
         v-model="newTodoText"
         id="new-todo"
         placeholder="리스트를 적어주세요"/>
  <button>추가</button>
</form>
<p v-for="(todo, index) in todos" :key="index">
  {{ todo.title }}
  <button @click="remove(index)">삭제</button>
</p>
data() {
  return {
    todos: [
      {id: 1, title: 'javascript'},
      {id: 2, title: 'vue.js'},
      {id: 3, title: 'react'}
    ],

    newTodoText: '',
    nextTodoId: 4,
  };
},

 methods: {
   addNewTodo() {
     this.todos.push({
       id: this.nextTodoId += 1,
       title: this.newTodoText
     })
     this.newTodoText = ''
   },
   remove(index) {
     return this.todos.splice(index, 1)
   }
},

addNewTodo 메소드는 객체형태로 push 해주는군

삭제 버튼에 클릭이벤트 걸어줄 때 remove(index) remove 메소드안에 index 넘겨줘야 함

 

해내따!!!

 

 

 

 

 

'Vue' 카테고리의 다른 글

[Vue] Slot  (0) 2022.03.17
[Vue] 인코딩 / 디코딩  (0) 2022.03.15
[Vue] Computed 속성  (0) 2022.03.12
[Vue] 클래스와 스타일 바인딩  (0) 2022.03.12
URL뒤에 붙는 #  (0) 2022.03.10