dou12754 2018-10-16 06:00
浏览 402

ajax调用后VueJS更新数据

I trying to do pagination on my webpage. So it will filter the data accordingly on every page is flipped. How can I update my Vue instance's data after every success ajax call? The correct data is passback on each ajax request is made but the Vue data did not update.

code in product.php (as below):

<script src="/vue.min.js"></script>
<script src="/i.js"></script>

<div class="content">
 <table class="hue">
  <thead>
    //table headings
  </thead>
  <tbody>
   <tr v-for="(value, key) in result">
     <td>{{value.productCode}}</td>
     <td>{{value.productName}}</td>
     //... etc
   </tr>
  </tbody>
 </table>
</div>

code in i.js (as below):

function fetchData(p=null){
 var ajaxVue = new Vue({
  el: ".hue > tbody",
  data: {
    result: []
  },
  mounted: function(){
   var self = this;
   $.ajax({
    url:"/a.php",
    method:"GET",
    data:{
     page: p
    },
    dataType:"json",
    success:function(rs){
     console.log(rs.pd[14].code);
     self.result = rs.pd;
     $('#pagination > .pagination').html(rs.pgnt);
     //ajaxVue.$forceUpdate();

    },
    error:function(err){console.log(err);}
   });
  }
 });
}

$(document).ready(function(){
  fetchData();
});

Note: the console.log() in ajax success function is to show whether the data is changing and correct data is fetch.

example:

//there will be 15 data on each request, i just show one for example.
BM23901 //current page: 1
BM19023 //current page: 2
BM39020 //current page: 3

but on my product.php interface, the shown data remain BM23901 instead of updating itself after each successful ajax request is made.

I tried forceUpdate() from Vue but the instance is still not updating.

  • 写回答

1条回答 默认 最新

  • doupo1890 2018-10-16 06:24
    关注

    I think you should use axios instead:

    try {
        const response = await axios({...});
        console.log(rs.pd[14].code);
        self.result = rs.pd;
    } catch (error) {
        console.log(error);
    }
    

    I think this code will work perfectly. But if you still wanna try it with ajax, then I might suggest changing your success function to arrow function:

    $.ajax({
        ...
        success: (resp) => {
            result = resp.pd;
        },
        ...
    });
    

    Notice that I dont have to use self inside arrow function

    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿