Vue 부모 컴포넌트에서 자식 컴포넌트의 이벤트 or 함수 직접 실행하기

박경준·2021년 11월 4일
0

vue beginner

목록 보기
12/18

ref를 이용해 해당 태그 혹은 컴포넌트에 직접 접근할 수 있음.

this.$refs로 ref 걸어둔 태그들 혹은 컴포넌트들에 접근할 수 있음.

this.$refs.child_component.$refs.btn.click(); 이벤트 호출 용법.

this.$refs.child_component.childFunc(); 함수 실행 용법

// /components/ChildComponent
<template>
  <button type="button" @click="childFunc" ref="btn">click</button>
</template>
<script>
export default {
  methods: {
    childFunc() {
      console.log("부모 컴포넌트에서 직접 발생시킨 이벤트");
    },
  },
};
</script>
// /components/ParentComponent
<template>
  <child-component @send-message="sendMessage" ref="child_component" />
</template>
<script>
import ChildComponent from "./ChildComponent";
export default {
  components: { ChildComponent },
  mounted() {
    // 자식 컴포넌트의 이벤트 호출
    this.$refs.child_component.$refs.btn.click();
    // 자식 컴포넌트의 함수 실행
    this.$refs.child_component.childFunc();
  },
};
</script>
profile
빠굥

0개의 댓글