【问题标题】:Can I get return value from vue custom directives?我可以从 vue 自定义指令中获取返回值吗?
【发布时间】:2019-02-18 21:27:49
【问题描述】:

我已经编写了制作谷歌地图的自定义指令。

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>

它有效,我可以看到地图。

然后,我想在地图上画一个标记,并且需要一个谷歌地图对象。

我可以从 v-gmap 指令中获取返回值吗?

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

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

它不起作用。

map 只是 HTML 元素..

【问题讨论】:

    标签: vue.js vue-directives


    【解决方案1】:

    您应该为此创建一个组件而不是指令:

    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"/>
    

    当然,这只是一个开始。如果您希望从组件外部控制标记,则可以通过道具传递标记;取决于您希望它如何运作。

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2013-08-19
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多