在vue-cli中使用axios时报错TypeError: Cannot set property 'lists' of undefined at eval

在vue-cli中使用axios拿取数据时

export default {
  data(){
    return{
      lists:{
      }
    }
  },
  methods: {
    getList(){
      axios.get('https://cnodejs.org/api/v1/topics',{
      })
      .then(function(response){
        window.console.log(response.data.data);
        this.lists = response.data.data;
      })
      .catch(function (error) {
        window.console.log(error);
      })
    }
  },
    beforeMount() {
    this.getList();
  },

报错

TypeError: Cannot set property 'lists' of undefined at eval (list.vue?51fc:19)

能get到数据,但无法传给lists数组

报错信息lists未定义,查找调试许久,发现是this指向问题。

在vue-cli里.then里使用function就会乱了this指向

把.then里function改用es6的写法就能正常传参了

.then((response)=>{
        window.console.log(response.data.data);
        this.lists = response.data.data;
      })

为什么用function定义就会乱this指向,奈何一时半会儿也没搞懂,留此疑惑,日后解答

猜你喜欢

转载自www.cnblogs.com/raonet/p/11581997.html