如何在渲染之前让我的组件等待ajax调用完成?现在,他们的数据对象是空的,因为挂载时ajax调用尚未完成。
此外,我希望所有组件都能访问此ajax数据,该数据将每30秒刷新和更新一次。实现这一目标的最佳方法是什么?
//Snippet of what gets return from ajax call
{
121: {
table_info: {
id: "121",
name: "Test",
table_number: "51",
cap: "6",
seating: "OPEN",
position_x: "0.19297285",
position_y: "0.07207237",
participants_in_tables: "5",
count: 5
}
}
}
//Global
var tableData; //This gets set when the Vue ajax call is complete after being mounted
var width = $(document).width();
var height = $(document).height();
//Vue
Vue.component('tables', {
data: () => {
return {
tables: tableData
}
},
template: `
<div id="tableContain">
<div class='table' v-for="table in tables" :style="computeOffsets(table)">
{{table.table_info.name}}
</div>
</div>
`,
methods: {
computeOffsets(table) {
return {
top: (table.table_info.position_x * width) + 'px',
left: (table.table_info.position_y * height) + 'px'
}
}
});
var app = new Vue({
el: '#main',
mounted() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'users/getTableAssignments/' + event_id
}).done(data => {
tableData = data; //Set global tableData
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="main">
<table></table>
</div>
答案 0 :(得分:1)
最好使用在vue中创建,然后在组件中使用道具获取数据,如:
Vue.component('tables', {
props: ['tables']
// ...
});
var app = new Vue({
el: '#main',
data: { tables: [] },
created() {
axios.get('url').then( response => { this.tables = response.data } )
}
});
我更喜欢axios但如果你愿意,你可以使用ajax:D
如果你想刷新你可以只使用间隔但我更喜欢服务器端解决方案,如套接字。我在我的应用程序中使用它与laravel广播,redis和套接字有一个实时仪表板:D