provider/inject:简单来说就是在父组件 provide 中提供变量,子组件 inject 中来注入,然后可以在子组件内部使用 provide 的变量
需要注意的是这里不论子组件有多深,只要调用了inject那么就可以注入provider中的数据。而不是局限于只能从当前父组件的prop属性来获取数据。
App.vue
<template>
<div id="app">
<div>
<second/>
</div>
</div>
</template>
<script>
import second from './components/Second'
export default {
name: 'app',
components: {
second
},
provide: {
test: 'App 根组件的 provide'
},
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>
Second.vue
<template>
<div>
<p>second: {{ test }}</p>
<third/>
</div>
</template>
<script>
import third from './Third.vue';
export default {
name: 'second',
components: {
third
},
inject: ['test'],
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>
Third.vue
<template>
<div>
<p>third: {{ test }}</p>
</div>
</template>
<script>
export default {
name: 'third',
components: {},
inject: ['test'],
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>