子组件使用父级属性和方法

<google-map>
  <google-map-region v-bind:shape="cityBoundaries">
    <google-map-markers v-bind:places="iceCreamShops"></google-map-markers>
  </google-map-region>
</google-map>

1.依赖注入

会使用两个实例选项:provide and inject


Vue.component('google-map', {
  provide: function () {
    return {
      getMap: this.getMap
    }
  },
  data: function () {
    return {
        map: null
    }
  },
  mounted: function () {
    this.map = new google.maps.Map(this.$el, { 
        center: { lat: 0, lng: 0 },
      zoom: 1
    })
  },
  methods: {
    getMap: function (found) {
      var vm = this
      function checkForMap () {
        if (vm.map) {
          found(vm.map)
        } else {
          setTimeout(checkForMap, 50)
        }
      }
      checkForMap()
    }
  },
    template: '<div class="map"><slot></slot></div>'
})

Vue.component('google-map-marker', {
  inject: ['getMap'],
  props: ['places'],
  created: function () {
    var vm = this
    vm.getMap(function (map) {
      vm.places.forEach(function (place) {
        new google.maps.Marker({
          position: place.position,
          map: map
        })
      })
    })
  },
  render (h) {
    return null
  }
})

2 $parent

var map = this.$parent.map || this.$parent.$parent.map
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容