vue3-provide和inject 通讯
基本语法
父组件声明
import { provide, reactive, ref } from 'vue'
setup() {
const geolocation = reactive({ longitude: 90, latitude: 135 })
provide('geolocation', geolocation) return { geolocation } },
子、孙组件使用
import { inject, reactive, ref } from 'vue'
setup() { const userGeolocation = inject('geolocation') return { userLocation, userGeolocation } } }
子级修改inject
场景:有时我们需要在子组件内部更新 inject 的数据。在这种情况下,我们建议 provide 一个方法来负责改变响应式
父组件:
setup() { const location = ref('North Pole')
const updateLocation = () => { location.value = 'South Pole' }
provide('location', location)
provide('updateLocation', updateLocation) }
子组件:
setup() { const userLocation = inject('location', 'The Universe') const userGeolocation = inject('geolocation') const updateUserLocation = inject('updateLocation') return { userLocation, userGeolocation, updateUserLocation } }
禁止子级修改inject
场景:如果要确保通过 provide 传递的数据不会被 inject 的组件更改,我们建议对提供者的 property 使用 readonly。
import { provide, reactive, readonly, ref } from 'vue'
setup() { const location = ref('North Pole') provide('location', readonly(location)) }