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.
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 }; } });
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

