- 자식 컴포넌트에서 부모 컴포넌트의 함수를 사용하려면?
- 부모 컴포넌트에서 자식 컴포넌트의 함수를 사용하려면?
- Vuex를 통해서 자식이 부모의 카운트 조절하기
- V-model을 통한 부모와 자식 컴포넌트 input 연결
자식 컴포넌트에서 부모 컴포넌트의 함수 사용하기 = emit
childComponent 자식컴포넌트
<template>
<div>
<h1>부모함수 자식컴포넌트에서 사용하기</h1>
<button @click="callParentFunction">자식에서 부모 함수 호출</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
callParentFunction() {
this.$emit('call-parent-function');
},
},
};
</script>
parentComponent 부모컴포넌트
<template>
<div>
<child-component @call-parent-function:"부모함수" />
</div>
</temlate>
<script>
methods: {
부모함수() {
console.log('부모 컴포넌트의 함수가 자식으로부터 호출되었습니다.
},
},
</script>
부모 컴포넌트에서 자식 컴포넌트의 함수 사용하기 = refs
childComponent 자식 컴포넌트
<template>
<div>
<h1>ChildComponent</h1>
</div>
</template>
<script>
export default{
methods:{
childfunction(){
console.log('부모에서 자식 함수 호출')
}
}
}
</script>
parentComponent 부모 컴포넌트
<template>
<div>
<button @click="부모에서사용하는자식함수" >부모에서 자식 함수를 부르는 버튼</button>
<child-component ref="childComponentRef" />
</div>
</temlate>
<script>
export default{
methods:{
부모에서사용하는자식함수(){
this.$refs.childComponentRef.childFunction()
}
}
}
</script>
Vuex를 통해서 자식이 부모의 카운트 조절하기
main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store';
Vue.config.productionTip = false;
new Vue({
store,
render: (h) => h(App),
}).$mount('#app');
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
decrease(state) {
state.count--;
},
},
});
export default store;
parentComponent 부모컴포넌트
<template>
<h1>Vuex를 이용하여 조절하는 카운터 : {{ this.$store.state.count }}</h1>
</template>
childComponent 자식컴포넌트
<template>
<div>
<h1>[3 컴포넌트] = Vuex</h1>
<div>
<button @click="increment">부모 카운트 +</button>
<button @click="decrease">부모 카운트 -</button>
</div>
</div>
</template>
<script>
export default {
methods: {
increment() {
this.$store.commit('increment');
},
decrease() {
this.$store.commit('decrease');
},
},
};
</script>
V-Model을 통한 부모와 자식 컴포넌트 연결
childComponent 자식컴포넌트
<template>
<div>
<h1>[2 컴포넌트] - V-Model</h1>
v-model을 이용하여 부모 컴포넌트와 연결
<input :value="value" @input="updateValue" />
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
},
test: {
type: String,
},
},
data() {
return {};
},
mounted() {
console.log(this.value, 'value');
},
methods: {
updateValue(event) {
this.$emit('input', event.target.value);
},
},
};
</script>
parentComponent 부모컴포넌트
<h2>
두번째 자식으로부터 받은 메세지
<p>입력 : <input v-model="parentValue" /></p>
<P>내용 : {{ parentValue }}</P>
</h2>
<child-component v-model="parentValue" />