vue3 provide inject

provide inject

vue3的provide inject其實和vue2差不多

在父組建上提供provide

可以是一個ref物件也可也是proxy物件也可以是一般的數據也可以是一個函式

子組建用inject接收

範例

#父
<script >
import HelloWorld from '@/components/HelloWorld.vue'
import { provide, reactive, ref } from 'vue'
export default {
  components: {
    HelloWorld
  },
  setup() {
    let msg = ref('msg')
    let person = reactive({
      name: 'jason'
    })
    provide('msg', msg)
    provide('person', person)
    provide('test', test)
    function test(){
      console.log('test')
    }
  }
}
</script>

<template>
  <HelloWorld></HelloWorld>
</template>
#子
<script >
import { inject } from "@vue/runtime-core"
export default {
  setup(props, context) {
    let msg = inject('msg','deafultValue') //ref
    let person = inject('person','deafultValue') //proxy
    let test = inject('test','deafultValue') // func
    test()
    return {
      msg, person
    }
  }
}

</script>
<template>{{ msg }}{{ person }}</template>

總結

只要是後代的組件都可以拿到前代組建provide的東西