In Vue 3, to access and modify variables within component functions, we typically use the Composition API, which is the recommended approach. The Composition API provides a more flexible way to organize component logic, particularly with the setup() function, which serves as the entry point for the Composition API.
1. Using ref and reactive
In Vue 3, ref and reactive are the two primary methods for declaring reactive variables.
refis used for defining reactive variables for primitive data types.reactiveis used for defining reactive variables for objects or arrays.
Example
Suppose we have a component that needs to handle a user's name and age, and perform certain operations based on this information.
vue<template> <div> <input v-model="name" placeholder="Enter your name"> <input v-model.number="age" placeholder="Enter your age" type="number"> <button @click="updateProfile">Update Profile</button> </div> </template> <script> import { ref } from 'vue' export default { setup() { const name = ref(''); // Declare a reactive string variable const age = ref(0); // Declare a reactive number variable // Define a function to update profile information function updateProfile() { console.log(`Updating profile with name: ${name.value} and age: ${age.value}`); // Further operations can be performed here, such as sending to a server } // Return all reactive data and methods required for the template within the setup function return { name, age, updateProfile }; } } </script>
2. Accessing and Modifying Variables
In the above example, you can see how we define reactive variables within the setup function and bind them to the template using v-model for two-way data binding. Within component functions, such as updateProfile, we can access and modify the values of these variables using the .value property.
This approach is ideal for managing component-local state while maintaining code organization and clarity.
Summary
By using Vue 3's Composition API, particularly the setup function in conjunction with ref and reactive, we can effectively define and access reactive variables within components while maintaining code modularity and maintainability. This approach not only makes state management intuitive but also facilitates managing complex component logic in large applications.