1、provide 和 inject
<template>
<div class="app">
我是app组件---(祖)
<h1>{{name}}--{{price}}</h1>
<son></son>
</div>
</template>
<script>
import son from './components/son.vue'
import {provide, reactive, toRefs} from 'vue'
export default {
name: 'App',
components: {
son
},
setup() {
let car = reactive({name: 'BMW', price: '40万'})
provide('car',car)
return {...toRefs(car)}
}
}
</script>
<style>
.app {
background: gray;
padding: 10px;
}
</style>
<template>
<div class="son">
我是son组件---(子)
<grandson></grandson>
</div>
</template>
<script>
import grandson from './grandson.vue'
import {reactive} from 'vue'
export default {
name: 'son',
components: {
grandson
},
setup() {
return {
}
}
}
</script>
<style>
.son {
background: skyblue;
padding: 10px;
}
</style>
<template>
<div class="grandson">
我是grandson组件---(孙)
<h1>{{name}}--{{price}}</h1>
</div>
</template>
<script>
import {inject, reactive, toRefs} from 'vue'
export default {
name: 'grandson',
setup() {
let car = inject('car')
return {...toRefs(car)}
}
}
</script>
<style>
.grandson {
background: #bfa;
padding: 10px;
}
</style>
注意:父子组件也是可以用provide/inject传参的,但是父子之间不建议用provide/inject,一般都是用props。如果grandson里面还有子组件,那么该子组件也是可以获取到app的car的
2、teleport
<template>
<div class="son">
我是son组件---(子)
<grandson></grandson>
<teleport to="body">
<div id="tm">111</div>
</teleport>
</div>
</template>
结论:将 #tm的div 传送到了body标签里面;to也可以是 css选择器。