Vue中使用Axios时Watch监听器未触发的问题求助
Hey there! Let's get to the bottom of why your autocompleteOn watcher isn't firing. The root cause here is how you're using Lodash's debounce with an arrow function in your method.
The Problem: Incorrect this Binding
Arrow functions don't bind their own this context—they inherit it from the outer scope. When you use an arrow function as the debounce callback, this won't point to your Vue component instance. That means your let $this = this line isn't capturing the right object, so any attempts to modify autocompleteOn won't actually update the component's data property (and thus the watcher never triggers).
The Fix: Use a Regular Function for Debounce
Replace the arrow function with a regular function in your debounce call. This ensures this correctly references your Vue component, so you can directly access and modify your data properties without hacks like $this:
export default { name: 'YourComponentName', data() { return { autocompleteOn: false } }, watch: { autocompleteOn(oldVal, newVal) { console.log('autocomplete watch triggered!', oldVal, newVal); } }, methods: { // Use a regular function here instead of arrow function fetchAutocompleteResults: _.debounce(function(filter) { const data = { filter: filter, page: this.somePageProperty // Now 'this' points to your Vue instance }; // Example Axios call (make sure you have this part in your code!) axios.post('/your-api-endpoint', data) .then(response => { // Update the data property correctly this.autocompleteOn = true; // Or set based on your API response }) .catch(error => { console.error('Fetch error:', error); }); }, 300) // Don't forget to add a debounce delay (e.g., 300ms) } }
Additional Checks
- Ensure you're actually updating
autocompleteOn: Double-check that your Axios.then()callback is correctly settingthis.autocompleteOnto a new value (watchers only trigger when the value changes from its current state). - Debounce delay: Make sure you pass a delay value to
_.debounce(like the300in the example above)—without it, the debounce won't work as expected.
内容的提问来源于stack exchange,提问作者Mikołaj Marciniak

