Vue中data用函数时后端响应返回Getter&Setter而非实际值问题
Hey there! Let's break down what's going on with your Vue data confusion—it's a common hiccup when you're starting out, so don't stress.
First, why does Vue require data to be a function for components?
The core reason is reusability. If you use an object for data, every instance of that component will share the exact same object reference. That means if one instance changes the data, all other instances will inherit that change too—total chaos for reusable components! Using a function ensures each component instance gets its own fresh, isolated copy of the data object.
Why are you seeing Getter & Setter instead of actual values?
When Vue initializes your component, it takes the object returned by your data() function and wraps it in a reactive proxy. This proxy adds Getter and Setter methods to every property so Vue can track changes automatically and update the DOM when data shifts.
When you log this proxy object to the console, it displays those Getters/Setters first—but the real data is absolutely there! Try expanding the object in your console (click the little arrow next to it) and you'll find the raw data nested under something like [[Target]]. Or you can log JSON.stringify(yourData) to see the plain, unproxied values.
Wait, why does using an object for data show actual values?
If you use an object instead of a function, Vue still converts it to a reactive proxy. But since there's only one shared object across all instances (if you ever reuse the component), the console might display it differently in some cases. This is a bad practice though—you're risking state leaks between component instances, so stick with the function approach!
How to use data correctly (and avoid confusion)
Here's a clean example of fetching data with a function-based data:
<template> <div>{{ apiData?.userName }}</div> </template> <script> export default { data() { return { apiData: null // Initialize with a placeholder }; }, async mounted() { // Fetch data from your backend const response = await fetch("/your-backend-endpoint"); const rawData = await response.json(); // Assign raw data to your reactive property this.apiData = rawData; // To see real values in console: console.log("Raw API response:", rawData); // Shows unmodified values console.log("Reactive data (raw):", JSON.stringify(this.apiData)); // Also shows real values console.log("Direct property access:", this.apiData.userName); // Works perfectly! } }; </script>
The big takeaway: even though the console shows Getters/Setters, you can still access the actual data by referencing properties directly (like this.apiData.userName) or using it in your template. The reactive proxy is just Vue doing its magic to keep your UI in sync with data changes.
Stick with the function-based data as the docs recommend—it's the right way to build stable, reusable components.
内容的提问来源于stack exchange,提问作者shibetoshii

