祖先组件可以通过provide选项,声明提供的数据。
后代组件可以通过inject选项,声明注入的数据。
不论组件层次有多深,在上下游关系成立的时间里始终生效。
一 App组件
<template>
<div>
<coffee type="卡布奇诺"/>
</div>
</template>
<script>
import Coffee from './coffee';
export default {
name: "App",
provide: {
brand: "雀巢"
},
components: { Coffee }
};
</script>
二 Coffee组件
<template>
<h4>{
{brand}} - {
{type}}</h4>
</template>
<script>
export default {
name: "Coffee",
inject: ["brand"],
props: {
type: String
}
};
</script>
三 运行效果