개발지식/vue.js
Vue 컴포넌트간 데이터 전달 emit props
kimty1121
2023. 10. 11. 00:37
같은 레벨에서의 컴포넌트 전달
<!-- HTML -->
<div id="app">
<app-header v-bind:app-title="message"></app-header>
<app-contents v-on:login="receive"></app-contents>
</div>
<!-- JavaScript -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
var appHeader = {
props: ['appTitle'],
template: '<h1>{{ appTitle }}</h1>',
}
var appContents = {
template: `
<p>
<button v-on:click="sendEvent">로그인</button>
</p>
`,
methods: {
sendEvent() {
this.$emit('login');
}
}
}
// 루트 컴포넌트
Vue.createApp({
data() {
return {
message: ''
}
},
methods: {
receive() {
console.log('받았다');
this.message = '로그인 됨'
}
},
components: {
// '컴포넌트 이름': 컴포넌트 내용
'app-header': appHeader,
'app-contents': appContents
}
}).mount('#app');
</script>
싱글 컴포넌트 에서의 데이터 전달
App.vue
<template>
<div>
<!-- <app-header v-bind:프롭스 속성 이름="상위 컴포넌트의 데이터 이름"></app-header> -->
<app-header
v-bind:propsdata="str"
v-on:renew="renewStr"></app-header>
</div>
</template>
<script>
import AppHeader from './components/AppHeader.vue';
export default {
data: function() {
return {
str: 'Header'
}
},
components: {
'app-header': AppHeader
},
methods: {
renewStr: function() {
this.str = 'hi';
}
}
}
</script>
<style>
</style>
components/AppHeader.vue
<template>
<header>
<h1>{{ propsdata }}</h1>
<button v-on:click="sendEvent">send</button>
</header>
</template>
<script>
export default {
props: ['propsdata'],
methods: {
sendEvent: function() {
this.$emit('renew');
}
}
}
</script>
<style>
</style>
출처
https://github.com/joshua1988/learn-vue-js/blob/master/vue3/same-component-level.html
https://github.com/joshua1988/learn-vue-js/blob/master/vue-cli-complete/src/App.vue
https://github.com/joshua1988/learn-vue-js/blob/master/vue-cli-complete/src/components/AppHeader.vue