子组件可以访问父组件的方法和属性,但是如果子组件内部还有多个组件,内部的子组件就无法访问父组件的方法,为了解决这个问题,就引入了依赖注入:
<google-map>
<google-map-region v-bind:shape="cityBoundaries">
<google-map-markers
v-bind:places="iceCreamShops"
></google-map-markers>
</google-map-region>
</google-map>
例如:google-map组件定义一个getMap的方法,google-map-region子组件可以访问父组件google-map的getMap的方法,但是google-map-markers组件就无法访问google-map的getMap的方法,因为?$parent ?property 无法很好的扩展到更深层级的嵌套组件上。这也是依赖注入的用武之地,它用到了两个新的实例选项:provide ?和?inject 。
provide ?选项允许我们指定我们想要提供给后代组件的数据/方法,
<google-map> ?内部的?getMap ?方法:
provide: function () {
return {
getMap: this.getMap
}
}
然后在任何后代组件里,我们都可以使用?inject ?选项来接收指定的我们想要添加在这个实例上的 property: 在google-map-region 、google-map-markers组件上使用inject
inject: ['getMap']
?代码示例:
google-map组件
<template>
<div class="column_style border_style div_layout">
google-map 组件
<slot></slot>
</div>
</template>
<script>
export default {
name: "google-map",
data() {
return {};
},
provide: function () {
return {
getMap: this.getMap,
};
},
methods: {
getMap() {
return "父组件getMap 方法访问成功 ";
},
},
};
</script>
<style scoped>
.div_layout{
height: 380px;
padding: 5px;
}
</style>
google-map-markers组件
<template>
<div class="column_style border_style">
google-map-markers 组件
<input type="button" value="获取父组件的getMap" @click="getParentMap" />
<span class="color_red"> {{ message }}</span>
<slot></slot>
</div>
</template>
<script>
export default {
name: "google-map-markers",
data() {
return {
message: "",
};
},
inject: ["getMap"],
methods: {
getParentMap() {
this.message = this.getMap();
},
},
};
</script>
google-map-region组件调用getMap方法和google-map-markers组件一样
|