vue3 - emit사용법

developer.do·2023년 5월 21일
1

emit

const emit = defineEmits =['toggle-todo','delete-todo'] 로 미리 설정을 할 수 있음.

부모컴포넌트

<script setup>
import TodoSimpleForm from "../pages/TodoSimpleForm.vue";
import TodoList from "../pages/TodoList.vue";

const todos = ref([]);
const toggle = ref(false);
const onToggle = () => {
  toggle.value = !toggle.value;
};

const addTodo2 = (todo) => {
  todos.value.push(todo);
};
// 자식컴포넌트에서 받아온 addTodo2이다. 여기서 인자에 있는 todo는 자식컴포넌트에서 보낸 것이다.

const deleteTodo = (index) => {
  todos.value.splice(index, 1);
};

const toggleTodo = (index) => { 
  todos.value[index].completed = !todos.value[index].completed;
};
</script>
<template>
  <div>
    <h1 class="text-35px my-15">TODOLIST</h1>
    <button @click="onToggle">Toggle</button>

    <!-- <TodoSimpleForm @add-todo="addTodo" /> -->
    <TodoSimpleForm @add-todo="addTodo2" />
      // 자식에서 보낸 add-todo를 @로 받아온다음, 그 데이터를 addTodo2라는 함수로 사용한다.
      
    <TodoList
      :todos="todos"
      @toggle-todo="toggleTodo"
      @delete-todo="deleteTodo"
    />
    <!-- :이름="데이터" -->
    <div v-if="todos.length === 0" class="text-blue">
      추가된 Todo가 없습니다.
    </div>
  </div>
</template>

<style scoped></style>

자식1 컴포넌트

<script setup>
const todo = ref("");
const hasError = ref(false);

const emit = defineEmits(["add-todo"]);

const onSubmit = () => {
  if (todo.value === "") {
    hasError.value = true;
    return;
  } else {
    emit("add-todo", {id: Date.now(),subject: todo.value,completed: false,});
    // 1. 여기서 emit을 통해서 자식 -> 부모로 데이터를 보낸다.
  }
  hasError.value = false;
  todo.value = "";
};
</script>
<template>
  <div>
    <form @submit.prevent="onSubmit">
      <input v-model="todo" class="bg-white p-3 b-1 w-100 b-black" />
      <button type="submit" class="bg-green p-3 b-1">Add</button>
    </form>
    <div v-if="hasError" class="text-red">This Field Can't Empty</div>
    <span v-else class="p-2"></span>
  </div>
</template>

<style lang="scss" scoped></style>

emit2

자식컴포넌트

const toggleTodo = (index) =>{
  emit('toggle-todo', index);
}
// index라는 값을 toggle-todo 라는 이름으로 보냄( 자식 -> 부모 )

부모컴포넌트
<todoList @toggle-todo="toggleTodo"/>

  const toggleTodo =(index) =>{
	todos.value[index].completed = true
  }
  //    아까 자식컴포넌트에서 보낸 index의 값이 여기 위의 인자 index에 들어오는 것임
   

emit3

자식컴포넌트

const deleteTodo =(index) =>{
 emit('delete-todo', index) 
}
부모컴포넌트

<TodoList @delete-todo="deleteTodo" />
  
const deleteTodo = (index) =>{
  todos.value.splice(index,1)
}

여기서 console.log(index)를 해보면 자식컴포넌트에서 보낸 index값이 올라옴

0개의 댓글