为什么基于vue-property-decorator的最小TS-Vue模板报keyword未定义错误
问题排查
- 缺失
@Component装饰器:使用vue-property-decorator编写类式组件时,必须给组件类添加@Component装饰器,否则类内部声明的属性不会被Vue识别为响应式实例属性,模板无法正常读取 - 访问修饰符限制:你代码中给
keyword加了private私有访问修饰符,该属性仅允许在类内部访问,而Vue模板属于类外部的渲染逻辑,部分TS编译配置下会禁止私有属性暴露到组件实例上 - 版本不匹配:
vue-property-decorator仅适配Vue2生态,若你的项目是Vue3版本,该库的API无法正常工作,类属性不会被正确注册到实例上
修复方案
若项目使用Vue2
补充@Component装饰器,调整keyword的访问修饰符即可,修复后代码如下:
<template> <div>{{ keyword }}</div> </template> <script lang="ts"> import { Vue, Component } from 'vue-property-decorator' @Component export default class Page extends Vue { keyword = '' } </script>
若项目使用Vue3
Vue3官方不再推荐类式组件,若仍需使用类式写法,需替换为适配Vue3的vue-facing-decorator库,修复后代码如下:
<template> <div>{{ keyword }}</div> </template> <script lang="ts"> import { Vue, Component } from 'vue-facing-decorator' @Component export default class Page extends Vue { keyword = '' } </script>
内容的提问来源于stack exchange,提问作者thousands_sun
相关产品推荐
相关产品推荐

