How can I get a result from a POST request into a v-for? - vue.js

I have something like this:
<table class="table">
<tbody>
<tr v-for="(option, index) in Weapons">
<td>Primary</td>
<td>[[ getWeaponType(option.WeaponType) ]]</td>
</tr>
</tbody>
</table>
In my Vue object, in methods, I have this:
getWeaponType: function(weaponTypeNumber){
axios.get('/path/to/api')
.then(response => {
return response.data
})
}
I send an ID and it returns the name for that ID. But I need for it to show in my table whose rows are being generated by the v-for. This isn't working since it is a Promise and the values are not showing. Is there any way I can achieve getting that value to show in the table? I didn't want to do it server side so I'm trying to see if I have any options before I do that.

May I suggest an alternative method?
data() {
return {
weaponsMappedWithWeaponTypes: [];
}
}
mounted() { // I am assuming the weapons array is populated when the component is mounted
Promise.all(this.weapons.map(weapon => {
return axios.get(`/path/to/api...${weapon.weaponType}`)
.then(response => {
return {
weapon,
weaponType: response.data
}
})
).then((values) => {
this.weaponsMappedWithWeaponTypes = values
})
}
computed: {
weaponsAndTheirWeaponTypes: function () {
return this.weaponsMappedWithWeaponTypes
}
}
And then in your template
<table class="table">
<tbody>
<tr v-for="(option, index) in weaponsAndTheirWeaponTypes">
<td>Primary</td>
<td>option.weaponType</td>
</tr>
</tbody>
</table>

Related

Failed returning data from array

i have a problem which that i cannot see the data inside array that i have pushed the data inside .then from axios
Here are the sample code
Axios from vue.js
export default {
name: 'facts',
data(){
const test = [{id: 'test',name: 'test'}]
const response = [];
const factsData = () => {
axios.get('http://localhost:3000').then(x=>response.push(x.data))
}
factsData();
console.log(response)
return{
test,
response
};
}
};
When i tried to console.log the output data inside the promise(.then) it worked well and display the data that i expected like this
and this is what happen when i tried to push the data from axios to response and show the output data in console.log with my current code above
when i tried to access it (console.log(response[0]), it shows undefined in console.log.
But strangely, when i back to my previous code to not to tried to access the data and i expand the array in console browser, it shows data that i expected which mean i couldn't access it.
The main purpose is i want to dipsplay the data to be rendered in table using v-for
<template>
<div class="about">
<center>
<table>
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr v-for="(user,index) in test" :key="user.id">
<td>{{index + 1}}</td>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
</tr>
</tbody>
</table>
</center>
</div>
</template>
Please tell me what i'm missing. Thank you.
P.S : I'm new to this vue js
your code structure is not correct. use this code:
export default {
name: 'ProfilePage',
data() {
return {
response: []
}
},
created () {
this.getData();
},
methods: {
getData() {
axios.get('http://localhost:3000').then(x => this.response = x.data);
}
}
}

Vue in laravel 5.8, populate table dynamically from axios response

I have a blade where I'm using a multiselect as dropdown, and when a selection is chosen it fires off an axios call which returns a json_encoded data set.
The blade is here:
<div class="uk-width-1-2">
<multiselect
label="name"
track-by="value"
v-model="CategoryValue"
:options="CategoryOptions"
:multiple="false"
:taggable="true"
#tag="getItems"
#input="getItems"
#search-change="val => read(val)"
:preselect-first="false"
:close-on-select="true"
:preserve-search="true"
placeholder="Choose Category..."
></multiselect>
<div style="border:1px solid black; height:80%; margin-top:15px;">
<table>
<thead>
<tr>
<th>Text</th>
</tr>
</thead>
<tbody v-for="build in buildsList">
<tr>
<td>#{{ build.build_code_formatted }}</td>
</tr>
</tbody>
</table>
</div>
</div>
new Vue({
data() {
return{
buildsList: {},
}
},
methods: {
getItems() {
console.log(this.CategoryValue.value);
axios.post('/getItems',{
categoryCode: this.CategoryValue.value,
})
.then(function (response){
this.buildsList = response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
})
And upon the callback I get a 200 and It does indeed log the buildsList so I know it is returning all of my data properly. However, when I get my data back in the console, it's not populating the html.
When I inspect the page elements there is no table body or data rows.
Also, my controller is returning this:
unction getItems(Request $request){
return json_encode($this->itemService->getItems($request->Code));
}
and itemService is doing this:
$results = $pdoStatement->fetchAll();
foreach ($results as &$r)
$r = (object) $r;
return $results;
So my data is coming back upon axios Call and it is formatted properly, but I just need to figure out why my table isn't dynamically populating
Please try to change this part
this.buildsList = response.data;
to
.then((response) => {
let data = response.data;
for (let key in data) {
if(data.hasOwnProperty(key)) {
this.$set(this.buildsList, key, data[key]);
}
}
})

Calling a method into another method in vue

I'm trying to call a method from inside another method in vue.
What I get is an undefined in my console, but what I really want is the id that is called in the getId function
In a whole what I'm tring to do is use the addEvent function to get the checkbox events so that I can get a true or false from it and then send that to the saveCheckbox function and from the saveCheckbox function call the getId function to get the ID of that specific checkbox.
I hope I was able to explain it properly. If it's still unclear please let me know.
This is what I have
<template>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Active</th>
<th scope="col">Title</th>
</tr>
</thead>
<tbody>
<tr v-for="(category, index) in categories" >
<td>
<input name="active" type="checkbox" v-model="category.active" #change="getId(category.id)" #click="addEvent">
</td>
<td>
{{ category.title }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: [
'attributes'
],
data(){
return {
categories: this.attributes,
}
},
methods: {
getId(id){
console.log(id);
return id
},
saveCheckbox(event){
console.log(this.getId());
},
addEvent ({ type, target }) {
const event = {
type,
isCheckbox: target.type === 'checkbox',
target: {
value: target.value,
checked: target.checked
}
}
this.saveCheckbox(event.target.checked)
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
You have to pass argument (Id) to getId method
Having a sort overview, you are not passing any Id to the method, and it trys to return that id. so maybe, that is what is not defined ?
The method calling is done well. with the this. keyword before it

Vuejs and datatables: table empty when using v-for to fill data

I'm trying to fill a datatable using vuejs v-for directive and ajax to get the data but the table is always showing "No data available in table" even though there are some data shown and also in the bottom says "Showing 0 to 0 of 0 entries". I guess this is because vuejs is reactive and the table can't recognize the changes maybe?
I've been searching and trying for a while but with no solution found..
thanks a lot! :)
here's the template:
<table id="suppliersTable" class="table table-hover table-nomargin table-bordered dataTable">
<thead>
<tr>
<th>...</th>
...
</tr>
</thead>
<tbody>
<tr v-for="supplier in suppliers">
<td>{{ supplier.Supplier_ID }}</td>
<td>...</td>
...
</tr>
</tbody>
</table>
and the vue and ajax:
<script>
export default {
data() {
return {
suppliers: [],
}
},
methods: {
fetchSuppliers() {
this.$http.get('http://localhost/curemodules/public/suppliers/list')
.then(response => {
this.suppliers = JSON.parse(response.bodyText).data;
});
}
},
created() {
this.fetchSuppliers();
},
}
Once initialized, DataTables does not automatically reparse the DOM. Here's a relevant FAQ:
Q. I append a row to the table using DOM/jQuery, but it is removed on redraw.
A. The issue here is that DataTables doesn't know about your manipulation of the DOM structure - i.e. it doesn't know that you've added a new row, and when it does a redraw it will remove the unknown row. To add, edit or delete information from a DataTable you must use the DataTables API (specifically the row.add(), row().data() and row().remove() methods to add, edit and delete rows.
However, you can call table.destroy() to destroy the current instance before reinitializing it. The key is to delay the reinitialization until $nextTick() so that Vue can flush the DOM of the old DataTables. This is best done from a watcher on suppliers so that the DataTables reinitialization is done automatically when the variable is updated in fetchSuppliers().
mounted() {
this.dt = $(this.$refs.suppliersTable).DataTable();
this.fetchSuppliers();
},
watch: {
suppliers(val) {
this.dt.destroy();
this.$nextTick(() => {
this.dt = $(this.$refs.suppliersTable).DataTable()
});
}
},
demo
I know this is a bit late answer but I just encountered this problem just today and my only solution for this issue is using setTimeout function.After fetching data using axios I set a bit of delay then init the data-table. With this work around v-for works fine.
See below for my code.
GetDepartmentList(){
axios.get('department')
.then((response) => {
this.departmentList = response.data;
// this.dataTable.rows.add(response.data).draw();
setTimeout(() => $('#department-data-table').DataTable(), 1000);
})
.catch((error) => {
if (error.response.status == 401) {
alert('User session has expired. Please login again.');
location.replace("/login");
}
});
},
Also you can use .rows.add() function if you want to draw row data in the table without using v-for of vue. Refer to this doc.
You can using Axios in Vuejs, you try see the following above:
<template>
<div class="danhsach">
<h2>{{title}}</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Password</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for='data in datas'>
<td>{{data.id}}</td>
<td>{{data.name}}</td>
<td>{{data.password}}</td>
<td>{{data.age}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default{
data(){
return {
title:"Tile Lists",
datas:[]
}
},
created:function(){
this.danhsach_user();
},
methods:{
danhsach_user(){
this.axios.get('https://599f807effe73c0011b9fcc5.mockapi.io/api/user').then((response)=>{
this.datas=response.data;
});
}
}
}
</script>

vuejs how can i pass my data back to view please

Can any one assist with why i cant get my array into the following please
HTML:
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Email</td>
<td>Password</td>
</tr>
</thead>
<tbody>
<tr v-if="email" v-for="mail in email" :key="">
<td>{{ allMyUsers.id }}</td>
<td>{{ allMyUsers.name }}</td>
<td>{{ allMyUsers.email }}</td>
<td></td>
</tr>
</tbody>
</table>
I'm calling my results as follows, i can see that the array is passed through my log (I think) but really strugging to understand my problem
Script:
import axios from 'axios';
export default {
computed: {
allMyUsers () {
return !this.$store.getters.alluser ? false : this.$store.getters.alluser
},
},
created () {
this.$store.dispatch('allUsers')
}
}
My code for getting the data is as follows and definately returns the data as I can see it in the log, just not sure if im passing it out
allUsers ({commit, state}) {
if (!state.idToken) {
return
}
globalAxios.get('/users.json')
.then(res => {
const data = res.data
const allUsers = []
for (let key in data) {
const user = data[key]
user.id = key
allUsers.push(user)
}
commit('storeUser', allUsers)
})
.catch(error => console.log(error))
}
My getter is as follows
getters: {
alluser (state) {
return state.allUsers
},
}
})
Any support very much appreciated as im new to vue so very much still learning
Many thanks for the help so far, I have tried to follow your guidance but nothing is returned and i now have no errors
my updated code is as follows, I was sure I d followed the guidance you kindly provided
HTML:
<tr v-if="myuser" v-for="myuser in allMyUsers" :key="">
<td>{{ myuser.email }}</td>
<td></td>
</tr>
SCRIPT:
<script>
import axios from 'axios';
export default {
computed: {
allMyUsers () {
return !this.$store.getters.myuser ? false : this.$store.getters.myuser
},
},
created () {
this.$store.dispatch('allMyUsers')
}
}
</script>
GETTER:
myuser (state) {
return state.myuser
},
Function:
allMyUsers ({commit, state}) {
if (!state.idToken) {
return
}
globalAxios.get('/users.json' + '?auth=' + state.idToken)
.then(res => {
const data = res.data
const myusers = []
for (let key in data) {
const myuser = data[key]
myuser.id = key
myusers.push(myuser)
}
commit('storemyuser', myusers)
})
.catch(error => console.log(error))
}
And finally my MUTATION:
storemyuser (state, myuser) {
state.myuser = myuser
},
Thankyou again for your assistance, you guys really are great at helping newbes like me learn
Your v-for loop is not good, email property is not defined in your component, you only defined a computed allUsers property (with getters from your store). It's this one you need to use :
<tr v-if="user" v-for="user in allUsers" :key="">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td></td>
</tr>