<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.依賴注入
會(huì)使用兩個(gè)實(shí)例選項(xiàng):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