美文网首页
子组件使用父级属性和方法

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

作者: 小杰的简书 | 来源:发表于2018-11-24 10:48 被阅读0次
<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

相关文章

网友评论

      本文标题:子组件使用父级属性和方法

      本文链接:https://www.haomeiwen.com/subject/xrlsxqtx.html