就在刚刚,我遇到了一个新的问题

刚在跟着Vue的官网写例子,在《通过 Prop 向子组件传递数据这一部分》 中,不是有相关的网络请求的一个小例子嘛,我就照着栗子写出了下面的代码
<template>
  <div>
    <a-button type="primary" @click="httpRequest"></a-button>
    <p>{{posts}}</p>
  </div>
</template>

<script>
export default {
  name: 'parent',
  data: function () {
    return {
      posts: []
    }
  },
  created: function () {
    this.httpRequest()
  },
  methods: {
    httpRequest () {
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then(function (response) {
          return response.json()
        })
        .then(function (data) {
          this.posts = data
          console.log(self.posts)
        })
    }
  }
}
</script>

<style>
</style>

但是,在我运行的时候出现了下面的错误在这里插入图片描述
???,不是说数据是要放在data中的吗,通过this来引用当前类的属性也是没错的啊,我期间换了好几种写法,均是这样的报错,我最终在栈爆上找到了答案。

栈爆上的解决方法

那位老哥的意思是,this在网络请求的异步代码块中的this与当前数据所在类的this不是一个作用域,所以会导致undefined。 老哥推荐使用箭头函数,或者在后方加bind(this),我选择了箭头函数,下面函数是我经过修改过后的样子
    httpRequest () {
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then(function (response) {
          return response.json()
        })
        .then((data) => {
          this.posts = data
          console.log(self.posts)
        })
    }
我特地去查了一下什么是箭头函数,MDN上说,箭头函数不绑定this,同时箭头函数中使用this,js会沿着传递链一直向上找到实际的this。
希望这篇文章可以帮到需要的各位同志们,如果有理解的不对的地方,也希望大家多多指教。
Logo

前往低代码交流专区

更多推荐