【发布时间】:2018-01-20 15:32:23
【问题描述】:
在mounted() 上,我进行了一个ajax 调用,它会提取特定于div 的数据,例如屏幕上的位置。问题是我从 ajax 数据设置 v-bind:style 的自定义方法在 ajax 完成之前运行,因此没有数据可以从中提取。 ajax 完成后设置样式的最佳方法是什么?
Ajax 调用返回如下内容: [{name: 'table1', top: 10, left: 25},{name: 'table2', top: 30, left: 100}]
$(function() {
var app = new Vue({
el: '#main',
data: {
tables: []
},
methods: {
computeOffsets() {
return { top: this.tables.top + 'px', left: this.tables.left+ 'px'}
}
},
mounted() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'tables/getTables/' + event_id
}).done(data => {
console.log(data);
this.tables = data;
});
}
});
});
.table {
position: absolute;
}
<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.min.js"></script>
<div id="main">
<div class='table' v-for="table in tables" v-bind:style="computeOffsets()">
{{table.name}}
</div>
</div>
【问题讨论】: