首页 > 解决方案 > jQuery 数据表与 Vue.js 有问题

问题描述

我在 laravel 项目中使用 Vue.js 中的 jQuery 数据表。数据已在数据表中很好地重新加载。但问题是加载数据表后的数据检索。因为,在数据表的第一行中说“没有任何数据”!我应该怎么做才能在 Vue.js 中使用 jQuery 数据表?

app.js 文件:

export const platform= {
    el:'#platform',

    data: {
        name:'',
        platforms: [],
    },

    methods: {
        index:function() {
            axios.get('/api/platforms', {
                headers: headers
            }).then(response => {
                this.platforms = response.data.data;
                this.dataTable.row.add([
                    this.platforms
                ]);
            }).catch(error => {
                alert(error.response.data.message);
            })
        },

        store:function() {
            axios.post('/api/platforms', {
                params: {
                    name: this.name
                }
            }, {
                headers: headers
            }).then(response => {
                this.platforms.push(response.data.data);
                alert(response.data.message);
            }).catch(error => {
                if (error.response.status === 422) {
                    this.message = error.response.data.data['validation-errors']['params.name'];
                } else {
                    this.message = error.response.data.message;
                }
            })
        },
    },

    mounted:function() {
        this.index();
    },
};

platform.blade.php 文件:

<section class="content" id="platform">
  <div class="form-group">
      <input type="text" v-model="name">
   </div>
   <button class="btn btn-raised" @click.prevent="store()">save</button>

   <div class="row">
     <table class="table table-bordered table-striped table-hover dataTable">
       <thead>
         <tr>
           <th>platform name</th>
         </tr>
         </thead>
          <tbody>
            <tr v-for="(platform, index) in platforms">
             <td>@{{ platform.name }}</td>
            </tr>
          </tbody>
      </table>
   </div>
</section>

标签: javascriptvue.jsdatatables

解决方案


对于反应性,您必须platformsdata()部分中进行初始化以设置所有必要的 getter/setter - 这是由 Vue 在后台完成的。

this.platforms并在使用 API 响应更新时分配一个新的数组引用。

data: {
    name:'',
    platforms: []
},

...
index:function() {
        axios.get('/api/platforms', {
            ...
        }).then(response => {

            // assign a new array reference in 'this.platforms'
            this.platforms = [ ...response.data.data];
            ...
        }).catch(...)
    },

...
store:function() {
        axios.post('/api/platforms', 
          ...
          ...
        ).then(response => {

           // assign a new array reference in 'this.platforms'
           this.platforms = [...response.data.data];
            alert(response.data.message);
        }).catch(...)
    },
},

...


推荐阅读