Vue 부모 컴포넌트에서 자식 컴포넌트의 데이터 옵션 값 동기화하기

박경준·2021년 11월 4일
0

vue beginner

목록 보기
15/18

computed를 사용한 데이터값 동기화

// /views/ChildComponent5
<template>
  <button type="button" @click="childFunc">
    자식 컴포넌트 데이터 변경
  </button>
</template>
<script>
export default {
  data() {
    return {
      msg: "메시지",
    };
  },
  methods: {
    childFunc() {
      this.msg = "변경된 메시지";
    },
  },
};
</script>
// /views/ParentComponent5
<template>
  <button type="button" @click="checkChild">자식 컴포넌트 데이터 조회</button>
  <child-component ref="child_component" />
</template>
<script>
import ChildComponent from "./ChildComponent5";
export default {
  components: { ChildComponent },
  // $refs를 통해 child_component 컴포넌트에 접근하여 msg data를 감시하고, this.msg를 업데이트함.
  computed: {
    msg() {
      return this.$refs.child_component.msg;
    },
  },
  methods: {
    checkChild() {
      alert(this.msg);
    },
  },
};
</script>
profile
빠굥

0개의 댓글