英文:
assigning a ref or reactive a typescript object and looping in vue 3
问题
我得到一个 TypeScript 对象的数组,并尝试进行简单的循环。我熟悉 Vue 2,但现在才开始使用 Vue 3。
我得到了一个 TestResponse TypeScript 对象的数组:
const props = defineProps({
test: Object as PropType<TestResponse[]>
})
const submit = async () => {
try {
const response = await api.getTest()
if (response != null) {
props.test = response.data; // 尝试分配给常量或只读变量
}
} catch (error) {
console.log('获取响应时出错:', error)
}
}
然后,我尝试简单地将它们打印出来:
<div class="text-white">
<div class="grid grid-cols-2 gap-4">
<div v-for="(item, index) in props.test">
{{ item.firstName }}
</div>
</div>
</div>
在循环遍历 response.data
时,除了控制台外什么都不打印。
英文:
I am getting an array of typescript objects and trying to do a simple loop. I am familiar with vue 2 but just now getting around to vue 3.
I get an array of TestResponse typescript objects
const props = defineProps({
test: Object as PropType<TestResponse[]>
})
const submit = async () => {
try {
const response = await api.getTest()
if (response != null) {
props.test = response.data. <---- Attempt to assign to const or readonly variable
}
} catch (error) {
console.log('Error while getting the response:', error)
}
}
then I simply try to print them out
<div class="text-white">
<div class="grid grid-cols-2 gap-4">
<div v-for="(item, index) in props.test">
{{ item.firstName }}
</div>
</div>
</div>
nothing prints except for the console when I loop over response.data
.
答案1
得分: 1
以下是翻译的内容:
你正在使用 props(只读属性)并尝试更新其值(这在 Vue 2 和 Vue 3 中都是错误的做法),因此你遇到了错误。另外,你试图在模板中使用 props.test
来访问测试对象(同样,在 Vue 2 和 Vue 3 中都是错误的做法),你可以直接在模板中访问 test
。
如果你想使用 props,那么请求应该在父组件上完成,测试对象应该传递给呈现数据的组件。此外,请记住不要在模板中使用 props.test
,你可以直接使用 test
访问它。
英文:
You are using props (readonly) and trying to update its value (this is wrong for Vue 2 and Vue 3), so you got that error, also, you are trying to access the test object using props.test
in the template (again, this is wrong for both, vue 2 and vue 3), you have access to test
directly in the template.
<template>
<div class="text-white">
<div class="grid grid-cols-2 gap-4">
<div v-for="(item, index) in test">
{{ item.firstName }}
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const test = ref<TestResponse[]>([])
const submit = async () => {
try {
const response = await api.getTest()
if (response != null) {
test.value = response.data // data should be TestResponse[] type
}
} catch (error) {
console.log('Error while getting the response:', error)
test.value = []
}
}
</script>
If you want to use props, then the request should be done on the parent component and the test object should be passed to the component that renders the data, also, remember to not use props.test
on the template, you have access to it directly using test
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论