i am trying ti access some data from jsonplaceholder using axios in vue and i created limit with select input that user can declare how many posts want to see and its defaul data in 10.the first time that page load everything works correctly and user can see 10 posts,but when choose another number for limits it doesnt work and there is 10 posts again.please help here is my code
<template>
<section >
<div v-if="loading" role="status">
<span >Loading...</span>
</div>
</section>
<router-link :to="{name:'createPost'}">Add Post</router-link>
<select v-model="selected" >
<option disabled value="">choose number of posts</option>
<option value="10">10 Posts</option>
<option value="20">20 Posts</option>
<option value="50">50 Posts</option>
<option value="100">All Posts</option>
</select>
<section v-if="!loading" v-for="post in posts" :key="post.id">
<Card :post="post" />
</section>
</template>
<script setup>
import axios from 'axios'
import {ref} from "vue";
import Card from "@/components/posts/Card";
let loading = ref(true)
let posts = ref([])
let selected =ref('10')
function userReq(){
axios.get(`https://jsonplaceholder.typicode.com/posts?_limit=${selected.value}`)
.then(response=> {
posts.value = response.data
loading.value=false
console.log('response',response)
})
.catch(()=>console.log('error'))
}
userReq()
</script>
<style scoped>
</style>
CodePudding user response:
Are you calling your fetch method in any way after changing the value? It only seems to be called on the initial load of the component. Try changing your select to the following:
<select v-model="selected" @change="userReq">
<option disabled value="">choose number of posts</option>
<option value="10">10 Posts</option>
<option value="20">20 Posts</option>
<option value="50">50 Posts</option>
<option value="100">All Posts</option>
</select>
Note the @change="userReq"
part. This ensures that whenever the "change" event fires (on selection of new value) it will call the userReq function again and update your posts.