My problem is with using an Axios response in Vue.js; it seems that the data is not saved to the array (newBox
).
I want to save API-returned values to an array for use with v-for
in the component.
<script setup>
import {
RouterLink,
RouterView
} from 'vue-router';
import {
onMounted,
onUnmounted
} from 'vue'
import Box from './components/Box.vue';
import axios from "axios"
import {
propsToAttrMap
} from '@vue/shared';
var newBox = new Array();
onMounted(() => {
getPosts();
})
async function getPosts() {
try {
const url = `https://someurl.ir/api/v1/api.php`
const response = await axios.get(url)
this.newBox = response.data
}))
} catch (err) {
if (err.response) {
// client received an error response (5xx, 4xx)
console.log("Server Error:", err)
}
}
}
</script>
<template>
<div class="NewBoxRibbon">
<Box v-for="title in newBox" :msg="title" />
</div>
<RouterView />
</template>
<style scoped>
.NewBoxRibbon{
scrollbar-width: 0px;
width: 100%;
height: 450px;
background-color: aquamarine;
overflow-x: auto;
white-space: nowrap;
}
::-webkit-scrollbar {
width: 0;
/* Remove scrollbar space */
background: transparent;
/* Optional: just make scrollbar invisible */
}
</style>
I used fetch
and it too seems that in function getPosts
it couldn't modify the array newBox
...
Even when I define a variable and try to modify it in the function getPosts
, can't do!!
Define newBox
as a ref property then update by reponse newBox.value = response.data
:
import {
onMounted,
onUnmounted,
ref
} from 'vue'
// ....
var newBox = ref([]);
//....
const response = await axios.get(url)
newBox.value = response.data