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方法注入

posted @ 2021-12-20 22:28  王小美丶  阅读(7589)  评论(0编辑  收藏  举报