Vue3 Composition API的script setup中通过Store Getter获取的data.name为undefined但模板可正常渲染
undefined Issue with Computed Getter Data in Vue 3's Script Setup Hey there! I see exactly where you're tripping up—let's sort this out step by step.
1. You're missing .value for the computed ref
First off, when you create a computed property in Vue 3's Composition API (including <script setup>), it returns a reactive ref object, not the raw value directly.
In your template, Vue automatically "unwraps" refs for you, so {{ data.name }} works just fine. But in the <script setup> code, you have to explicitly access the underlying value using .value.
Your original code:
const data = computed(() => store.getters['projectSettings/getData']); console.log(data.name); // ❌ Tries to access a 'name' property on the ref object itself
Fixed version:
const data = computed(() => store.getters['projectSettings/getData']); console.log(data.value.name); // ✅ Accesses the actual data inside the ref
2. Handling asynchronous data loading
Even with .value, you might still see undefined if your API call hasn't finished yet—since the getter is pulling data that's loaded asynchronously.
To safely work with this data once it's available, you have a couple solid options:
Option A: Use watch to react to data changes
Set up a watcher to run code only when the data (or the ref) updates:
import { watch } from 'vue'; const data = computed(() => store.getters['projectSettings/getData']); watch(data, (newData) => { if (newData) { // Make sure the data exists before accessing properties console.log(newData.name); } }, { immediate: true }); // Run the watcher once immediately on component mount
Option B: Optional chaining to avoid errors
If you just want to log without waiting for the data to load, use optional chaining to prevent runtime errors when the data is still undefined:
console.log(data.value?.name); // Won't throw an error if data.value is null/undefined
Quick recap
- Always use
.valuewhen accessing ref/computed values directly in<script setup> - Account for asynchronous data loading with watchers or optional chaining to avoid
undefinedissues
内容的提问来源于stack exchange,提问作者kate9247

