vue3获取组件实例

  |  

非 script setup语法时,回调可以拿到

export default {
setup(props, context) {
// Attributes (Non-reactive object, equivalent to $attrs)
console.log(context.attrs)

// Slots (Non-reactive object, equivalent to $slots)
console.log(context.slots)

// Emit events (Function, equivalent to $emit)
console.log(context.emit)

// Expose public properties (Function)
console.log(context.expose)
}
}

script setup语法需要采用下面的方式

getCurrentInstance的使用

(官方警告)只暴露给高阶使用场景,典型的比如在库中。强烈反对在应用的代码中使用 getCurrentInstance。请不要把它当作在组合式 API 中获取 this 的替代方案来使用。getCurrentInstance 只能在setup或生命周期钩子中调用。

<script setup lang='ts'>
import { getCurrentInstance } from 'vue'
const internalInstance = getCurrentInstance()

nternalInstance.appContext.config.globalProperties // 访问 globalProperties
</script>

但是这样智能获取到根的实例

internalInstance下的proxy属性会指向组件的实例,拿的时候会发现没有想要的东西, 因为vue默认是不代理你自定义的一些数据的,需要使用defineExpose将数据抛出去(其实就是告诉vue代理这些数据)

<script setup lang="ts">
import {ref} from "vue"
const width = ref<number>(100)
defineExpose({
...props,
width,
})
</script>

暴露之后,就可以通过internalInstance.proxy拿到了

特别注意

千万不要使用internalInstance.ctx作为this的代替使用,生产环境是会出事的

封装成hook使用

import {ComponentInternalInstance, getCurrentInstance} from "vue"

export default function useCurrentInstance() {
const {appContext, proxy} = getCurrentInstance() as ComponentInternalInstance

const globalProperties = appContext.config.globalProperties

return {
proxy,
appContext,
globalProperties
}
}

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 非 script setup语法时,回调可以拿到
  2. 2. getCurrentInstance的使用
  3. 3. 特别注意
  4. 4. 封装成hook使用
,