• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

Child Component member function access

22.05.12 16:55 작성 조회수 114

1

안녕하세요.
먼저 유용한 강의 감사합니다.
강의를 바탕으로 프로젝트를 진행하고 있습니다. 

제가 Naver Map Api를 이용해 주소를 기반으로 대락젹인 위치를 잡고, 지도를 통해 정확한 위치를 잡고자 컴포넌트를 작성했습니다. 

import NaverMap from "@/components/External/NaverMap/NaverMap";

const map = {
    install( Vue ) {
        const clientId = process.env['VUE_APP_X_NCP_APIGW_API_KEY_ID'];
        if( !clientId ) return;
        const URL = `https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=${clientId}`;
        const script = document.createElement('script');
        script.setAttribute('src', URL);
        script.id = 'naver-map-load';
        script.setAttribute('async', '');
        script.setAttribute('defer', '');
        document.head.appendChild(script);
        Vue.component('naver-map', NaverMap);
    }
}

export default map;

지도 컴포넌트에서는 지도가 로드되면 지도 컴포넌트 자신을 상위 컴포넌트에 $emit 함수를 통해 전달합니다.

  methods: {
    genCenter() {
      return this.map.getCenterPoint();
    },
    createMap() {
      let options = {};
      options.zoom = 17;
      if( this.options.longitude && this.options.latitude ) {
        options.center = new window.naver.maps.LatLng(this.options.latitude, this.options.longitude);
      }
      this.map = new window.naver.maps.Map(this.map_content_id, options);
      window.naver.maps.Event.addListener( this.map, 'center_changed', event => this.$emit( 'center_changed', event ) )
      window.naver.maps.Event.addListener( this.map, 'centerPoint_changed', event => this.$emit( 'centerPoint_changed', event ) )
      this.$emit('loaded', this );
    }
  }

위 코드에서 발생된 'loaded' 이벤트가 상위 컴포넌테에 전달되면 전달된 컴포넌트를  data에 저장합니다. 그리고 'center_changed' 이벤트가 발생하면 기존 전달된 컴포넌트 객체의 getCenter 함수를 통해 맵의 중심좌표를 가져와 data 설정하도로록 되어 있습니다.

    onLoadMap( map ) {
      this.map = map;
    },
    onCenterChanged() {
      const map = this.map;
      const center = map.getCenter();
      this.center.longitude = center.x;
      this.center.latitude = center.y;
    },

그러나 data의 map 변수의 'getCenter' 함수에 접근할 수 없습니다. 디버그를 통해 보니 map 변수는 Proxy라는 기존 컴포넌트를 감싸고 있어 바로 접근이 안됩니다.
위 부분을 어떻게 처리하면 좋을까요?

 

답변 1

답변을 작성해보세요.

0

안녕하세요, 하위 컴포넌트 인스턴스를 가리키고 있는 this를 상위 컴포넌트에서 받아 내부 메서드를 조작하시려고 하시는거죠? 이건 컴포넌트 통신 방식의 표준에 위배되는 구조라 지양하셔야 합니다.