박봉진
박봉진

Reputation: 149

Can I get return value from vue custom directives?

I have writen custom directive that make a google map.

Vue.directive('gmap', {
  inserted: function (el) {
    return new google.maps.Map(el, {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8
    })
  }
})

<div v-gmap ref="map" style="height: 360px"></div>

It works and I can see the map.

And then, I want to draw a marker on the map, and need a google maps object for it.

Can I get return value from v-gmap directives?

mounted () {
    const map = this.$refs.map

    const marker = new google.maps.Marker({
      position: { lat: -34.397, lng: 150.644 },
      map: map,
      title: 'Hello World!'
    });
  }

It doesn't works.

map is just HTML element..

Upvotes: 1

Views: 1022

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

You should create a component instead of a directive for this:

Vue.component('gmap', {
  template: '<div/>',

  mounted() {
    this.map = new google.maps.Map(this.$el, {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8,
    });

    const marker = new google.maps.Marker({
      map: this.map,
      position: { lat: -34.397, lng: 150.644 },
      title: 'Hello World!',
    });
  },
});
<gmap style="height: 360px"/>

This is just a start, of course. You can pass in markers through a prop if you want the markers to be controlled externally from the component; it's up to you how you want it to function.

Upvotes: 1

Related Questions