I'm new at coding in general, and i have this exercise where i need to bring a single additional user from an API (with name and image data) each time someone clicks on the button. I tried everything from hiding and and trying to show them one by one but i can't seem to find a way. This is my last attempt so far, i'm using vue js and j queary
`html code`
<body>
<div id="app">
<h1>Lista de usuarios</h1>
<div >
<div id="box">
<div v-for="item in (users.data)">
<img
v-bind:src=" item.avatar "
alt="Imagen usuario"
/>
<p>{{ item.first_name }} {{ item.last_name }}</p>
</div>
<div id="newusers">
<div
v-for="item in (users2.data)"
style="display: none"
>
<img
v-bind:src=" item.avatar "
alt="Imagen usuario"
/>
<p>{{ item.first_name }} {{ item.last_name }}</p>
</div>
</div>
</div>
</div>
<button type="button" v-on:click="addUser">
Agregar nuevo usuario
</button>
</div>```
`js code`
```var userApp = new Vue({
el: "#app",
data: {
users: {},
users2: {},
},
methods: {
addUser: function (event) {
$("#newusers").append("<p>" userApp.users2.data.first_name[0] "</p>");
},
},
});
$.ajax({
url: "https://reqres.in/api/users",
dataType: "json",
success: function (data) {
userApp.users = data;
},
});
$.ajax({
url: "https://reqres.in/api/users?page=2",
dataType: "json",
success: function (data) {
userApp.users2 = data;
},
});```
CodePudding user response:
You should not use jQuery with Vue. You can try with fetch
var userApp = new Vue({
el: "#app",
data() {
return {
users: [],
page: 1,
perPage: 6,
total: 0
}
},
computed: {
hasMore() {
return this.total > this.users.length
}
},
methods: {
addUser(event) {
this.page
this.getUsers(this.page, 1)
},
getUsers(page, nr) {
fetch("https://reqres.in/api/users?page=" page "&per_page=" nr)
.then(response => response.json())
.then(data => {
this.total = data.total
this.users = [...this.users, ...data.data]
});
}
},
mounted() {
this.getUsers(this.page, this.perPage)
this.page = this.perPage
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div id="app">
<h1>Lista de usuarios</h1>
<div >
<div id="box">
<div v-for="item in (users)" :key="item.id">
<img
v-bind:src=" item.avatar "
alt="Imagen usuario"
/>
<p>{{ item.first_name }} {{ item.last_name }}</p>
</div>
</div>
</div>
</div>
<button type="button" v-on:click="addUser" v-if="hasMore">
Agregar nuevo usuario
</button>
</div>