如何读取console log中PrimeVue组件的props等内部属性值
原因说明
你遇到的IDE报错是TypeScript类型检查导致的:PrimeVue导出的PrimeButton组件的公开TS类型中,仅暴露了name这类通用属性,props属于组件构造器的内部配置属性,没有被包含在默认导出的类型定义里,但该属性在运行时实际存在。
解决方案
分两种使用场景对应处理:
场景1:读取组件预设的props配置定义
如果需要读取PrimeButton组件官方预设的所有props配置项,用类型断言绕过TS检查即可:
// 方案1:简便写法,临时绕过TS检查 console.log((PrimeButton as any).props) // 方案2:规范类型断言,使用Vue官方类型 import { type DefineComponent } from "vue" console.log((PrimeButton as DefineComponent).props)
场景2:读取页面渲染后的组件实例props值
如果需要读取当前页面上已经渲染出来的PrimeButton实例的props实际值,需要通过ref获取组件实例再读取:
<template> <!-- 给组件添加ref属性 --> <PrimeButton ref="primeBtnRef" label="示例按钮" /> </template> <script lang="ts"> import { defineComponent } from "vue" import PrimeButton from "primevue/button" const Component = defineComponent({ components: { PrimeButton }, mounted() { // 通过ref获取实例后读取props console.log(this.$refs.primeBtnRef?.$props) }, }) export default Component </script>
内容的提问来源于stack exchange,提问作者DnD2k21
相关产品推荐
相关产品推荐

