如何在 vue 3 中呈现 API 响应的列表?
How do I render a list on API response in vue 3?
我是 vue 的新手,正在尝试从 API 响应
中呈现项目列表
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import ServiceCard from './components/ServiceCard.vue'
import { parse, stringify } from 'yaml'
import { onMounted, onUpdated } from 'vue'
import Vue from 'vue'
interface ServiceAPIResponse { host: string, protocol: string, services: [{ subdomain: string, apikey: string }] };
let yaml: ServiceAPIResponse;
onMounted(() => {
fetch('https://api.my.domain/').then((resp) => {
resp.json().then((data: ServiceAPIResponse) => {
yaml = data;
console.log(yaml);
});
});
});
onUpdated(() => {
console.log('onupdated');
});
</script>
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png" />
<ul v-if="yaml">
<li v-for="service in yaml.services" :key="service.subdomain">
<ServiceCard :name="service.subdomain" :host="yaml.host" :subdomain="service.subdomain" />
</li>
</ul>
</div>
</template>
来自 React,我希望在更新 yaml
的值时发生重新渲染。我试过用 reactive()
包装它,但我不太了解 vue。
我不明白为什么我的 v-if
在设置 yaml
的值后仍然是假的。
v-if
是处理这个问题的正确方法吗?
使用这段代码,我得到错误:
TypeError: Cannot read properties of undefined (reading 'services')
要成为反应式变量,必须将其包装在 ref 中(或反应式(目前对您来说区别不重要)),
在你的例子中,用一个空对象初始化你的变量
import { Ref, ref } from 'vue'
let yaml: Ref<ServiceAPIResponse> = ref({})
然后当你想分配新值时
yaml.value = data;
我是 vue 的新手,正在尝试从 API 响应
中呈现项目列表<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import ServiceCard from './components/ServiceCard.vue'
import { parse, stringify } from 'yaml'
import { onMounted, onUpdated } from 'vue'
import Vue from 'vue'
interface ServiceAPIResponse { host: string, protocol: string, services: [{ subdomain: string, apikey: string }] };
let yaml: ServiceAPIResponse;
onMounted(() => {
fetch('https://api.my.domain/').then((resp) => {
resp.json().then((data: ServiceAPIResponse) => {
yaml = data;
console.log(yaml);
});
});
});
onUpdated(() => {
console.log('onupdated');
});
</script>
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png" />
<ul v-if="yaml">
<li v-for="service in yaml.services" :key="service.subdomain">
<ServiceCard :name="service.subdomain" :host="yaml.host" :subdomain="service.subdomain" />
</li>
</ul>
</div>
</template>
来自 React,我希望在更新 yaml
的值时发生重新渲染。我试过用 reactive()
包装它,但我不太了解 vue。
我不明白为什么我的 v-if
在设置 yaml
的值后仍然是假的。
v-if
是处理这个问题的正确方法吗?
使用这段代码,我得到错误:
TypeError: Cannot read properties of undefined (reading 'services')
要成为反应式变量,必须将其包装在 ref 中(或反应式(目前对您来说区别不重要)),
在你的例子中,用一个空对象初始化你的变量
import { Ref, ref } from 'vue'
let yaml: Ref<ServiceAPIResponse> = ref({})
然后当你想分配新值时
yaml.value = data;