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

Vue.js中TypeScript环境下watch函数使用及JS转TS侦听器语法咨询

Hey there! Let's break down your questions step by step, with practical TypeScript examples tailored for Vue.js.

在Vue.js的TypeScript环境中使用watch函数

Whether you're using Options API or Composition API, TypeScript adds type safety to your watchers—here's how to do it right:

1. Options API Approach

Wrap your component with defineComponent so TypeScript can infer types correctly. Here's a complete example:

import { defineComponent } from 'vue';

export default defineComponent({
  // First, define typed props
  props: {
    branch_id: {
      type: String, // Swap with Number if your ID is numeric
      required: true // Mark as false if it's optional
    }
  },
  watch: {
    // Watch branch_id with explicit type annotations
    branch_id(newVal: string, oldVal: string) {
      console.log(`branch_id changed from ${oldVal} to ${newVal}`);
      // Add your business logic here
    },
    // For deep watching or immediate execution
    complexReactiveProp: {
      handler(newVal: YourCustomType, oldVal: YourCustomType) {
        // Handle deep changes
      },
      deep: true,
      immediate: true // Run handler when component mounts
    }
  }
});

2. Composition API Approach (Vue 3+)

Use the watch function alongside ref/reactive for more flexible, type-safe code:

import { defineComponent, ref, watch } from 'vue';

export default defineComponent({
  props: {
    branch_id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    // Optional: Convert prop to a mutable ref if needed
    const branchId = ref(props.branch_id);

    // Watch the prop directly
    watch(
      () => props.branch_id,
      (newVal: string, oldVal: string) => {
        console.log(`branch_id updated: ${oldVal} → ${newVal}`);
        branchId.value = newVal; // Sync to ref if needed
      }
    );

    // Watch a ref directly
    watch(branchId, (newVal) => {
      console.log(`branchId ref changed: ${newVal}`);
    });

    return {
      branchId
    };
  }
});

Convert Your JS Script to TS + Add Watcher Syntax

Here's your original JS code converted to TypeScript, with proper type annotations and a sample watcher:

import { defineComponent } from 'vue';

// Wrap with defineComponent for TypeScript support
export default defineComponent({
  // Define typed props (adjust type based on your actual use case)
  props: {
    branch_id: {
      type: String,
      required: false // Set to true if it's a mandatory prop
    }
  },
  watch: {
    // Add a watcher for branch_id with type safety
    branch_id(newVal: string | undefined, oldVal: string | undefined) {
      if (newVal) {
        console.log(`Current branch_id: ${newVal}`);
        // Add your logic here—like fetching data or updating state
      }
    }
  }
});

If branch_id is a numeric value, just change type: String to type: Number and update the parameter types to number | undefined.


内容的提问来源于stack exchange,提问作者mai elrefaey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:10:25