본문 바로가기
frontend/vue

[Hoon] Vuejs 강의 - v-for 와 컴포넌트

by 플로거 2020. 5. 13.

v-for 와 컴포넌트

https://kr.vuejs.org/v2/guide/list.html#v-for-와-컴포넌트

v-for를 컴포넌트에 직접 사용할 수 있습니다.

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <todo-item v-for="todo in todos" v-bind="todo" :key="todo.id"></todo-item>
  <br>
  <todo-item v-for="todo in todos" v-bind:id="todo.id" v-bind:text="todo.text" :key="todo.id"></todo-item>
</div>
Vue.component('todo-item', {
	props: ['text', 'isComplete'],
  template: '<li>{{ text }}, {{ isComplete }}</li>'
})

new Vue({
  el: '#app',
  data: {
    todos: [
    	{
      	id: 1,
        text: 'Learn Vue',
        isComplete: false
    	},
      {
      	id: 2,
        text: 'Take out the trash',
        isComplete: false
    	},
      {
      	id: 3,
        text: 'Mow the law',
        isComplete: false
    	}
    ]
  }
})

2.2.0 이상에서 v-for는 key 가 필수 입니다.

컴포넌트에 item을 자동으로 주입하지 않는 이유는 컴포넌트가 v-for의 작동 방식과 밀접하게 결합되기 때문입니다.
데이터의 출처를 명확히 하면 다른 상황에서 컴포넌트를 재사용할 수 있습니다.

<div id="app">
  <form v-on:submit.prevent="addNewTodo">
    <label for="new-todo">Add a todo</label>
    <input
      v-model="newTodoText"
      id="new-todo"
      placeholder="E.g. Feed the cat"
    >
    <button>Add</button>
  </form>
  <br>
  <todo-item
    v-for="(todo, index) in todos"
    v-bind:item="todo"
    v-bind:index="index"
    v-bind:key="todo.id"    
    v-on:remove="todos.splice(index, 1)">
  </todo-item>
</div>
Vue.component('todo-item', {
  template: '\
    <li>\
      {{ item.text }}\
      <button v-on:click="$emit(\'remove\')">Remove</button>\
    </li>\
  ',
  props: ['item'],
});

new Vue({
  el: '#app',
  data: {
    todos: [
      {
        id: 1,
        text: 'Do the dishes',
      },
      {
        id: 2,
        text: 'Take out the trash',
      },
      {
        id: 3,
        text: 'Mow the lawn',
      },
    ],
    nextTodoId: 4,
    newTodoText: '',
  },
  methods: {
    addNewTodo: function () {
      this.nextTodoId = this.todos.length;
      this.todos.push({
        id: this.nextTodoId++,
        text: this.newTodoText,
      });
      this.newTodoText = '';
    },
  },
});

bit.ly/3fXOzon

 

인프런 인강 선착순 30% 마지막 할인 쿠폰 - Vue.js 핵심 강의!

강좌명 - [Vue.js 입문] Javascript Real 웹앱 개발 - 1부 : vue 개념 ~ 핵심 실습 인프런 인터넷 강의 선착순 100명 30% 할인쿠폰! 강의 수강평도 부탁드립니다. bit.ly/2TtRHis [Vue.js 입문] 초보 실전 웹앱 개..

plogger.tistory.com

 

 

bit.ly/2TtRHis

 

[Vue.js 입문] 초보 실전 웹앱 개발 - 1부 : vue 개념 ~ 핵심 - 인프런

이 강의를 수강하시면 Vue.js 와 관련된 기본적인 개념부터 Real 웹앱 개발을 해 볼 수 있습니다. 이 강의는 1부 기본기 이며, 2부와 3부를 통해서 실제 Real 웹앱을 구현해 보도록 하겠습니다. 초급 ��

www.inflearn.com

 

댓글