为何使用Vue从后端获取数据后一直赋值失败?-亲测

今天开始用mock.js和Vue前端进行交互了,然后获取到json数据之后赋值一直失败,困扰了自己好几个小时

   clickHandler(e){
     var that = this;
     this.$axios.get("/news")
     .then(res{
       console.log(res.data);
       let data_ = JSON.stringify(res.data,  null, 4);
       //去除mock对象的数据列表
       this.items = res.data.list;
       console.log(this.items)
     })
     .catch(err=>{
       console.log(err)
     })
     this.isShow=true;
     console.log(this.items)
   }

我在获取到json数据后是这样处理的,然后item数组一直是空的,
在这里插入图片描述
无论我如何改变值。其实奥秘在这里

            .then(function(res){
              let data_ = JSON.stringify(res.data,  null, 4);
              //去除mock对象的数据列表
              this.items = res.data.list;
            })

注意此时的this是什么?是你的Vue对象吗?还是axios对象?在这里调用this.items只会给当前对象赋值,并不会给你的Vue对象的数据赋值,我们有两种解决方案:

  • 使用=>
    .then(res=>{
      let data_ = JSON.stringify(res.data,  null, 4);
      //去除mock对象的数据列表
      this.items = res.data.list;
    })
  • 在函数开始前记录this指针
   var that = this;
   this.$axios.get("/news")
   .then(res=>{
     let data_ = JSON.stringify(res.data,  null, 4);
     //去除mock对象的数据列表
     that.items = res.data.list;
   })

数据成功显示
在这里插入图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值