从API获取数据,将数据注入Vue ref并在html模板中使用

问题描述 投票:0回答:1

我是前端新手,只是尝试一下。我按照教程和 vue 示例创建了一个简单的 Web 应用程序。我现在想用从后端获取的数据填充下拉选择框。但无论我尝试什么,它都不起作用,并且失败了

TheSandbox.vue:18 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'sendOptions')
。不幸的是,教程中的所有 vue 示例都是针对静态数据集的。我在这里缺少什么?代码如下:

应用程序.vue

<script setup>
import TheHeader from './components/TheHeader.vue'
import TheSandbox from './components/TheSandbox.vue';
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <TheHeader msg="You did it!" />
    </div>
  </header>

  <main>
    <TheSandbox />
  </main>
</template>

TheSandbox.vue

<script setup>
import { ref } from 'vue'

const sendAmount = ref('')
const sendSelected = ref('')
const sendOptions = ref([])

async function fetchItems() {
    return fetch('<MYURL>', {
        method: 'GET',
        headers: {
            "Content-Type": "application/json",
        },
    }).then(response => {
        console.log(response)

        response.json().then(data => {
            this.sendOptions = data.map(item => ({
                value: item.code, // actual value for the option
                text: item.name, // display text for the option
            }))

            console.log(data)
        });
    }).catch(err => {
        console.error(err);
    });
}

import { onMounted } from 'vue'
import { nextTick } from 'vue'

onMounted(async () => {
    // Fetch the data first
    await fetchItems();

    // Use await nextTick to wait until the DOM is updated
    await nextTick();

    // Now, you can interact with the DOM if necessary (e.g., selecting a default option)
    console.log('DOM updated and options are rendered');
})
</script>

<template>
    <div class="item">
        <div class="details">
            <h3>
                You send {{ sendAmount }} {{ sendSelected }}
            </h3>
            <input v-model="sendAmount" placeholder="0" />
            <select v-model="sendSelected">
                <option v-for="option in sendOptions" :key="option.value" :value="option.value">
                    {{ option.text }}
                </option>
            </select>
        </div>
    </div>
</template>

谢谢!

vue.js vuejs3
1个回答
0
投票

参考

sendOptions
sendOptions.value
:

sendOptions.value = data.map(item => ({
        value: item.code, // actual value for the option
         text: item.name, // display text for the option
      }))

© www.soinside.com 2019 - 2024. All rights reserved.