Skip to content
此页目录
本文总阅读量

Vue Provide/Inject 祖孙传值

setup 中使用,需要 import 引入。

  • 祖先组件
js
// 使用 ref,reactive 是为了响应性 
const location = ref('North Pole')
const geolocation = reactive({
 longitude: 90,
 latitude: 135
})

provide('location', location)
provide('geolocation', geolocation)

/* readonly 可以保证不被孙组件修改属性 */
provide('location', readonly(location))
  • 孙组件
js
/* 孙组件引入 inject */
const userLocation = inject('location', 'The Universe')
const userGeolocation = inject('geolocation')

评论

交流群