vue3 组件传参--后代传参(爷孙)
一、创建一个三层级的关系
二、将组件串联起来
在爷爷组件中引入爸爸组件,并使用
<template>
<div class="index">
<h1>我是爷爷</h1>
<one></one>
</div>
</template>
<script lang="ts" setup>
import one from "./one.vue
</script>
在爸爸组件中引入孙子组件,并使用
<template>
<div class="son">
<h1>我是爸爸</h1>
<two></two>
</div>
</template>
<script lang="ts" setup>
import two from "./two.vue"
</script>
三、在爷爷组件中发送数据provide
<template>
<div class="index">
<h1 :style="{color:colorX}">我是爷爷</h1>
{{ colorX }}
<div>
//点击那个colorX就被赋值那个值,来显示不同颜色
<button @click="colorX='red'">红色</button>
<button @click="colorX='green'">绿色</button>
<button @click="colorX='blue'">蓝色</button>
</div>
<one></one>
</div>
</template>
<script lang="ts" setup>
import one from "./one.vue"
//引入provide组合式api
import {ref,provide} from "vue"
let colorX = ref("red")
// provide("想要传递的属性名",传递的值)
provide("wwh",colorX)
</script>
四、在孙子组件中接受数据inject
<template>
<div class="sunzi">
<h1 :style="{color:msg}">我是孙子</h1>
</div>
</template>
<script lang="ts" setup>
import {ref,inject} from "vue"
// 接收数据 inject("接受的属性")
const msg = inject("wwh")
</script>
代码
1 index.vue(爷爷)
<template>
<div class="index">
<h1 :style="{color:colorX}">我是爷爷</h1>
{{ colorX }}
<div>
<button @click="colorX='red'">红色</button>
<button @click="colorX='green'">绿色</button>
<button @click="colorX='blue'">蓝色</button>
</div>
<one></one>
</div>
</template>
<script lang="ts" setup>
import one from "./one.vue"
import {ref,provide} from "vue"
let colorX = ref("red")
// provide("想要传递的属性名",传递的值)
provide("wwh",colorX)
</script>
<style lang="scss" scoped>
.index{
padding: 20px;
background: pink;
}
</style>
2 one.vue(爸爸)
<template>
<div class="son">
<h1>我是爸爸</h1>
<two></two>
</div>
</template>
<script lang="ts" setup>
import two from "./two.vue"
</script>
<style lang="scss" scoped>
.son{
padding: 20px;
background: yellow;
}
</style>
3 two.vue(孙子)
<template>
<div class="sunzi">
<h1 :style="{color:msg}">我是孙子</h1>
</div>
</template>
<script lang="ts" setup>
import {ref,inject} from "vue"
// 接收数据 inject("接受的属性")
const msg = inject("wwh")
</script>
<style lang="scss" scoped>
.sunzi{
padding: 20px;
background: skyblue;
}
</style>