본문 바로가기
Vue.js

[Vue.js] 부모가 가진 데이터 조작하기

by Yeoseungwon 2024. 1. 21.
728x90

props를 마음대로 변경하면 오류가 발생하는데, $emit과 사용자 정의 이벤트를 사용할 수 있다. 

 

▼부모의 템플릿

<div id="app"> 
    <ul>
        <child-component v-for="item in list"
                         v-bind:key="item.id" 
                         v-bind="item"
                         v-on:do-click="handleAlert"></child-component>
    </ul>
</div>

 

v-on:do-click 

에서 do-click을 카멜케이스(doClick)로 작성하면 오류가난다. 

v-on:do-click은 자식 컴포넌트 methods 중 do-click 을 호출한다. 

 

props로 ID 받고, $emit으로 매개변수를 전달할 수 있다. 

 

//자식이 자신의 이벤트 실행
Vue.component('child-component', {
    template: '<li>{{ name }} 나이:{{ age }}\
    <button v-on:click="doAlert">나이확인</button></li>',
    props:{ id: Number, name: String, age: Number},
    methods: {
        //버튼 클릭 이벤트 핸들러에서 $emit으로 doClick 호출하기
        doAlert: function(){
            //매개변수로 자신이 가진 ID 전달하기
            this.$emit('do-click', this.id)
        }
    }
})
//부모쪽에서 이벤트 받기
new Vue({
    el:'#app',
    data: {
        list: [
            {id: 1, name: '홍길동', age: 30},
            {id: 2, name: '김민지', age: 18},
            {id: 3, name: '이지호', age: 24}
        ]
    },
    methods: {
        //doClick 이 발생한 경우
        handleAlert: function(id){
            //매개변수 ID로 요소 검색하기
            var item = this.list.find(function(el){
                return el.id === id
            })
            //age 가 20보다 적으면 alert 이 뜸 
            if(item !== undefined && item.age < 20) {alert('청소년입니다.')}
            else {alert('성인입니다.')}
        }
    }
})

 

age값 확인 후 alert 이 뜸 

 

 

데이터 조작하기. 

부모 컴포넌트에서는 이벤트를 통해 받은 ID로 자신이 가진 데이터를 조작할 수 있다. 

//자식이 자신의 이벤트 실행
Vue.component('child-component', {
    template: '<li>{{ name }} 나이:{{ age }}\
    <button v-on:click="doAlert">나이확인</button></li>',
    props:{ id: Number, name: String, age: Number},
    methods: {
        //버튼 클릭 이벤트 핸들러에서 $emit으로 doClick 호출하기
        doAlert: function(){
            //매개변수로 자신이 가진 ID 전달하기
            this.$emit('do-click', this.id)
        }
    }
})
//부모쪽에서 이벤트 받기
new Vue({
    el:'#app',
    data: {
        list: [
            {id: 1, name: '홍길동', age: 30},
            {id: 2, name: '김민지', age: 18},
            {id: 3, name: '이지호', age: 24}
        ]
    },
    methods: {
        //doClick 이 발생한 경우
        handleAlert: function(id){
            //매개변수 ID로 요소 검색하기
            var item = this.list.find(function(el){
                return el.id === id
            })
            //age 가 20보다 적으면 나이가 +1 이 됨
            if(item !== undefined && item.age < 20) item.age += 1
        }
    }
})

 

 

728x90