Vue3+TS组件mounted钩子无法访问props属性theIdPost如何解决
Vue3 组件props在mounted中调用报TS2339错误原因解析
核心原因
- 该错误属于TypeScript静态类型检查错误,不影响代码实际运行,你的props定义和传值逻辑本身是正常的,因此模板中可以正常渲染
theIdPost的值。 - 触发报错的根因是你在使用Vue3的Options API写法编写TS组件时,没有用Vue提供的
defineComponent方法包裹导出的组件配置对象,导致TypeScript无法正确推导组件实例上绑定的props属性,无法识别你已经声明的theIdPost属性,因此抛出Property 'theIdPost' does not exist on type的类型错误。
修复方案
方案1:保留现有Options API写法,用defineComponent包裹配置对象
修改导出逻辑即可解决类型报错:
<script lang="ts"> import { computed, defineComponent } from 'vue'; import { store } from '../store/index'; // 新增defineComponent包裹 export default defineComponent({ name: 'comment', props: { theIdPost: Number, theTxtPost: String, theLike: Number, }, setup() { const myStore: any = store const commentList = computed(() => myStore.state.commentList); console.log("CommentList > " +commentList.value); return { commentList }; }, mounted() { const myStore: any = store; myStore.dispatch("getComments", {'id': this.theIdPost}); } }) </script>
方案2:使用<script setup>语法糖简化写法
<script setup>是Vue3官方推荐的写法,不需要手动包裹defineComponent,直接通过defineProps声明props即可直接访问,无需通过this调用:
<script setup lang="ts"> import { computed } from 'vue'; import { store } from '../store/index'; // 声明props const props = defineProps<{ theIdPost?: number theTxtPost?: string theLike?: number }>() const myStore: any = store const commentList = computed(() => myStore.state.commentList); console.log("CommentList > " + commentList.value); // 直接调用dispatch,setup执行时机早于mounted,props已可正常读取 myStore.dispatch("getComments", {'id': props.theIdPost}) </script>
内容的提问来源于stack exchange,提问作者RoosDev
相关产品推荐
相关产品推荐

