vue3 $parent獲取父組件的方法和值

  import { defineAsyncComponent, ref, provide } from 'vue'; // 父組件
  const emit = defineAsyncComponent(() => import('../../components/edit/index.vue'))
  const name = ref('1111')
  // const foo = Symbol('foo') // 這個方法有個bug就是 配套的多個組件同時使用實例不能只用一個key,每個實例要有不一樣的key,否則會被最後調用provide方法覆蓋掉
  // const bar = Symbol('foo') // 需要用Symbol()
  // console.log(foo === bar);
  provide('name', name)
  import { getCurrentInstance, inject, watch } from 'vue'; // 子組件
  const instance = getCurrentInstance()
  const _this = instance.appContext.config.globalProperties // 獲取全局對象\
  const name = inject('name')
  watch(name, (newValue, oldValue) => {
    console.log(name.value)
  })
  console.log(name.value)

調用 provide和inject方法注入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章