简体   繁体   中英

Fetched data is not populated in table [vue]

I am new to js/vue and I am trying to fetch data from an API. I have a field which value will be used to fetch data from the API for that keyword. I can see in the console log that I do get the data as an array. However, that data does not get populated in the table.

The odd thing that is worth mentioning is that if I make a slight change in the code, such as delete extra space and save...while I still have the browser open with the data fetched, then the table will get populated.

In the script I have:

let data;

const fetchData = async (inputString: string) => {
 data = await getData(inputString);
 console.log('Data', data);
 return data;
}

And the input field + button: <input v-model='inputString' placeholder='Write keyword here' /> <button action @click='fetchData(inputString)"> Fetch data </button>

Your data variable needs to be reactive for the template to know about changes.

import { ref } from 'vue';  
const data = ref<null|string>(null);

const fetchData = async (inputString: string) => {
 data.value = await getData(inputString);
 console.log('Data', data);
 return data.value;
}

In your template you can then simply use data like this:

<div>{{data}}</div>

See more about reactivity here: https://vuejs.org/guide/essentials/reactivity-fundamentals.html#reactive-variables-with-ref

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM