- 祖先组件
<template>
<el-button @click="gra = '爷爷我 变了!'">祖先改变</el-button>
{{gra}}
<A></A>
</template>
<script setup lang="ts">
import {ref,provide, readonly} from 'vue'
import A from './A.vue'
//提供的响应式状态使后代组件可以由此和提供者建立响应式的联系
const gra = ref<String>('我是祖先组件')
// provide(/* 注入名 */ 'message', /* 值 */ 'hello!')
provide('gra',readonly(gra))//如果不想后代组件改变这个值,加readonly
</script>
- 后代组件
<template>
<div class="container">
{{ child }}
{{ fromGra }}
</div>
<button @click="change">change</button>
</template>
<script setup lang="ts">
import {ref,inject,Ref} from 'vue'
const child = ref<string>('我是孙子组件')
const fromGra = inject<Ref<string>>('gra',ref('我是默认值!'))
// const fromGra = inject('gra')
const change = () => {
fromGra!.value = '我变了'
}
</script>
- css绑定变量,! 非空断言操作符,?可选链操作符
补充一下这章学到的新知识
css绑定变量:v-bind
<script setup lang="ts">
import {ref,inject,Ref} from 'vue'
const color = ref('skyblue')
const change = () => {
color.value = 'green'
}
</script>
<style scoped lang="scss">
.box{
width:100px;
height: 100px;
background-color: v-bind(color); //使用v-bind绑定script中的变量
color: white;
}
</style>
! 非空断言操作符
忽略 undefined 和 null 类型
const fromGra = inject<Ref<string>>('gra',ref('我是默认值!'))
const change = () => {
fromGra!.value = '我变了' //fromGra如果祖先组件没提供,可能为undefined
}
?可选链操作符
遇到 null
或 undefined
就可以立即停止某些表达式的运行
obj?.name