1) 전역 컴포넌트 생성
<div id="app">
<child-component></child-component>
</div>
<script>
Vue.component('child-component', {
props: ['propsdata'],
template: '<button v-on:click="showLog">show</button>',
methods: {
showLog: function() {
this.$emit('show-log')
}
}
});
</script>
2) 지역 컴포넌트 생성
<div id="app">
<local-component></local-component>
</div>
<script>
var cmp = {
template: '<div> 전역 컴포넌트입니다.</div>',
};
new Vue({
el: '#app',
// 지역 컴포넌트 등록
components: {
'local-component': cmp
}
)}
</script>
3) 컴포넌트 통신 ( 하위 -> 상위 )
<div id="app">
<child-component v-on:show-log="printText"></child-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
<script>
Vue.component('child-component', {
props: ['propsdata'],
template: '<button v-on:click="showLog">show</button>',
methods: {
showLog: function() {
this.$emit('show-log')
}
}
});
const app = new Vue({
el: '#app',
data: {
message: "Hello Vue!"
},
methods: {
printText: function() {
console.log("received Event")
}
}
});
</script>
4) 컴포넌트 통신 - 이벤트 버스
<div id="app">
<child-component></child-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
<script>
var eventBus = new Vue();
Vue.component('child-component', {
template: '<div>하위 컴포넌트 영역입니다.<button v-on:click="showLog">Show</button></div>',
methods: {
showLog: function() {
eventBus.$emit('triggerEventBus', 100);
}
}
});
const app = new Vue({
el: '#app',
created: function() {
eventBus.$on('triggerEventBus', function(value){
console.log("이벤트를 전달받음. 전달받은 값 : ", value);
});
}
});
</script>