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)) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端