You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 3 + Typescript 如何监听类组件的Prop属性

Vue3下vue-class-component的使用说明

  • 适配Vue3的是vue-class-component v8版本,目前该库处于维护状态,仅修复bug,不会新增功能,官方更推荐新业务使用组合式API开发。
  • 原@Prop、@Watch等装饰器已经从vue-class-component中剥离,需要额外安装适配Vue3的vue-property-decorator@^10.0.0版本才能使用,也可以直接在@Options配置项中完成对应逻辑,无需额外依赖。

方案1:无需额外依赖,直接在@Options中配置watch

<script lang="ts">
import { Options, Vue } from "vue-class-component";

@Options({
  props: {
    msg: String,
  },
  watch: {
    // 监听msg属性,可直接获取新旧值
    msg(newVal: string, oldVal: string) {
      console.log('msg发生变化', newVal, oldVal)
      // 此处编写监听处理逻辑
    },
    // 若需要深度监听/初始化立即触发,可写成对象配置
    /*
    msg: {
      handler(newVal: string, oldVal: string) {
        console.log('msg变化', newVal)
      },
      immediate: true, // 组件初始化时就触发一次回调
      deep: true // 若msg为对象/数组类型,需要开启深度监听
    }
    */
  }
})
export default class HelloWorld extends Vue {
  msg!: string;
}
</script>

方案2:使用@Watch装饰器写法

首先安装适配Vue3的装饰器依赖:
npm install vue-property-decorator@^10.0.0

组件代码示例:

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { Prop, Watch } from 'vue-property-decorator'

@Options({})
export default class HelloWorld extends Vue {
  // 用@Prop声明props
  @Prop({ type: String })
  msg!: string;

  // 监听msg属性
  @Watch('msg')
  onMsgChange(newVal: string, oldVal: string) {
    console.log('msg发生变化', newVal, oldVal)
    // 处理逻辑
  }

  // 可传入配置开启立即执行/深度监听
  /*
  @Watch('msg', { immediate: true, deep: true })
  onMsgChange(newVal: string, oldVal: string) {
    console.log('msg变化', newVal)
  }
  */
}
</script>

方案3:推荐的组合式API写法(

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:24:07