Stack Overflow Asked by JayK23 on February 21, 2021
I’m trying to create a component that, on page load, executes a request to my backend, receives some data and shows this data on a vuetify-datatable. I managed to get the data, but my table won’t show it, as it is just empty.
Here is the component:
<template>
<v-simple-table dark>
<template v-slot:default>
<thead>
<tr>
<th class="text-left">
Asset
</th>
<th class="text-left">
Total
</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in balances"
:key="item.asset">
<td>{{ item.asset }}</td>
<td>{{ item.total }}</td>
</tr>
</tbody>
</template>
</v-simple-table>
</template>
<script>
var balancesArr = []
fetch('http://127.0.0.1:8000/binance/getbalance')
.then(response => response.json())
.then(data => {
balancesArr = data
console.log(balancesArr)
})
export default {
data () {
return {
balances: balancesArr,
}
},
}
</script>
Here is main.js
:
import Vue from "vue/dist/vue.js";
import Vuex from "vuex";
import storePlugin from "./vuex/vuex_store_as_plugin";
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import Vuetify from "vuetify";
import "vuetify/dist/vuetify.min.css";
Vue.use(Vuetify);
Vue.use(Vuex);
Vue.use(storePlugin);
Vue.config.productionTip = false;
Vue.use(VueAxios, axios)
new Vue({
render: h => h(App)
}).$mount('#app')
And the html file:
<div id="app">
<app></app>
</div>
I successfully see the data being printed on my console, but nothing shows on the table. What am i doing wrong here?
Blockquote
You can use life-cycle hook mounted
to fetch data on initial page load.
export default {
data() {
return {
balances: [],
}
},
mounted() {
this.fetchData()
},
methods: {
fetchData() {
fetch('http://127.0.0.1:8000/binance/getbalance')
.then(response => response.json())
.then(data => {
this.balances = data
})
}
}
}
you can also use created
to fetch data on initial page created is executed before mounted for reference enter link description here e.g.
export default {
data() {
return {
balances: [],
}
},
created() {
this.fetchData()
},
methods: {
fetchData() {
fetch('http://127.0.0.1:8000/binance/getbalance')
.then(response => response.json())
.then(data => {
this.balances = data
})
}
}
}
Correct answer by Nilesh Patel on February 21, 2021
You are doing it wrong, you're not using vue correctly:
<script>
export default {
created() {
fetch('http://127.0.0.1:8000/binance/getbalance')
.then(response => response.json())
.then(data => {
this.balances = data
})
},
data () {
return {
balances: [],
}
},
}
</script>
Answered by Tomer on February 21, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP