【问题标题】:Bind Styles After Ajax CallAjax 调用后绑定样式
【发布时间】: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>

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    您需要将表格作为参数传递给computeOffsets 方法。

    <div class="table" v-for="table in tables" :style="computeOffsets(table)">
        {{ table.name }}
    </div>
    
    computeOffsets(table) {
        return { top: table.top + 'px', left: table.left + 'px' };
    }
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2015-09-13
    • 2014-04-16
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 2012-12-15
    • 2011-06-18
    相关资源
    最近更新 更多