provide / inject这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效
eg:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>slot</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
<div id='root'>
<parent>
<children1>
<children2></children2>
</children1>
</parent>
</div>
</body>
<script>
Vue.component('parent', {
template: `<div>
<slot></slot>
</div>`,
provide: {
foo: 'bar'
}
})
Vue.component('children1', {
template: `<span>{{foo}}
<slot></slot>
</span>`,
inject: ['foo']
})
Vue.component('children2', {
template: `<h1>{{foo}}</h1>`,
inject: ['foo']
})
var vm = new Vue({
el: '#root',
})
</script>
</html>