您的位置:首页技术文章
文章详情页

javascript - Vue2 Ajax(axios)分页更新dom数据不成功

【字号: 日期:2022-11-10 14:24:02浏览:50作者:猪猪

问题描述

由于在项目中,后台的数据一次性给前端,前端需要做一些分页的处理。用的是Vue2+Axios 来做ajax请求 目前可以得到后端的数据console.log打印成功,但就是更新不上dom上。

html

<section class='main'> <ul class='list'><li v-for='info in listt2'> <img src='https://www.haobala.com/wenda/2776.html#' v-bind:alt='info.Name'> <h4> <a target='_blank' v-bind:href='https://www.haobala.com/wenda/’content.html?’+info.id'>{{ info.title }}</a></h4> <span class='ckey'>【{{ info.key }}】 </span> <span style='color: #ffffff;'> {{info.id}}</span></li> </ul> <!--分页按钮区域--> <p v-show='onn'> <button @click='page(’last’)' v-show=’curPage>0’>上一页</button><button @click='page(’!last’)' v-show='curPage<pageCount-1'>下一页</button> </p></section>

JS

Vue.prototype.$ajax = axios; //修改原型链 var vm = new Vue({el: ’.main’,data: { listt2:[ ], //页面要展示的数据 pageSize:10, //翻页每页显示数据 curPage:0, //当前页面 pageCount:’’, //总共页面数 onn:true, //默认显示分页 items:’ ’, //后台数据 },created:function(){ //Ajax获取后台数据,获取的数据存储在 this.items var url = 'api.json'; this.$ajax.get(url).then(function (response) { var jsons = response.data.getJson; var self = this; this.items =jsons; console.log(self.items);}).catch(function (error) { console.log(error);}); this.fanye(); //调用分页},methods: { page: function (el) { //点击翻页el == ’last’ ? this.curPage-- : this.curPage++;var curtotal = this.curPage * this.pageSize;var tiaoshu = this.curPage * this.pageSize + this.pageSize;this.listt2 = this.items.slice(curtotal,tiaoshu);document.body.scrollTop = 0; }, fanye: function () { //分页处理var _this = this;_this.listt2 = [];if (_this.items) { _this.pageCount = Math.ceil(_this.items.length / _this.pageSize); for (var i = 0; i < _this.pageSize; i++) {if (_this.items[i]) { _this.listt2.push(_this.items[i]);} }} }}})

返回的模拟数据格式

{ 'getJson':[{ 'id':'59', 'key':'science', 'title':' 动物也是科技宅,这些智能科技装备你想要吗? ', 'time':'2017-05-12', 'name':'两个质子', 'eng':'lianggezhizi'},{ 'id':'60', 'key':'science', 'title':' 肯定你没见过的养老新科技! ', 'time':'2017-06-19', 'name':'老年健康生活方式', 'eng':'aged-expo'}]}

javascript - Vue2 Ajax(axios)分页更新dom数据不成功已检查多遍,仍是只有样式没有数据,还望大牛指点

问题解答

回答1:

created方法里面请求的第一个then里面,把var self = this; 提到this.$ajax.get(url) 上面,作用域的问题,then方法里面的this已经不再是vue里的this

回答2:

你created ajax数据获取是异步的,你this.fanye()执行的时候,根本没有数据传入; 你可以打断点,console.log数据,试一下先

标签: JavaScript
相关文章: