Middle
Tell about closures in JavaScript. Where are closures used in Vue 3?
sobes.tech AI
Answer from AI
In JavaScript, a closure is a function that "remembers" its lexical environment even when called outside its scope. This allows the function to access variables from an outer function after the outer function has finished executing.
Example of a closure:
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
In Vue 3, closures are used in the Composition API, for example, inside setup() functions. Variables and functions declared in setup are closed over and accessible in reactive computations and component methods.
Example in Vue 3:
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return { count, increment };
}
}
Here, increment closes over the variable count, maintaining access to it.