注意:
- 子组件不要直接通过赋值语句修改父组件暴露的数据
- 应该通过父组件暴露的set函数来修改
语法:
1. 非ts环境:
provide('名字',readonly(变量))
2. ts环境下标注类型:
const 名字 = Symbol() as InjectionKey<变量的类型>;
provide(名字,readonly(变量));3. 说明:
readonly()方法可省, 用来确保子组件不会赋值修改父组件的变量
实例:
<!-- src/components/MyMap.vue -->
<template>
<MyMarker />
</template>
<script>
import { provide, reactive, ref, readonly } from 'vue'
import MyMarker from './MyMarker.vue'
export default {
components: {
MyMarker
},
setup() {
const location = ref('North Pole')
const geolocation = reactive({
longitude: 90,
latitude: 135
})
const setLocation = (value) => {
location.value = value
}
provide('location', readonly(location))//readonly可以让变量为只读
provide('geolocation', readonly(geolocation))
provide('updateLocation', updateLocation)//还可以暴露方法,让子组件能修改父组件的数据
}
}
</script><!-- src/components/MyMarker.vue -->
<script lang="ts">
import { inject } from 'vue'
export default {
setup() {
const userLocation = inject<类型>('location', 'The Universe')//这里是显示标注类型,默认是自动推断类型
const userGeolocation = inject('geolocation')
const setUserLocation = inject('setLocation')
return {
userLocation,
userGeolocation,
setUserLocation
}
}
}
</script>