【问题标题】:TypeError when trying to assign axios response to data variable in Vue component尝试将 axios 响应分配给 Vue 组件中的数据变量时出现 TypeError
【发布时间】:2023-03-08 10:51:02
【问题描述】:

我在这一行收到TypeError: Cannot set property 'randomWord' of undefinedthis.randomWord = response.data.word;

console.log(response.data.word) 会打印出一个字符串。

Vue 组件:

<template>
  <div>
    <h2>Wordnik Random Word</h2>
    <button class="button" @click="getWord">Random Word</button>
    <p>The random word is: {{ randomWord }}</p>
  </div>
</template>

<script>
const axios = require('axios')

export default {
  name: 'RandomWord',
  data() {
    return {
      randomWord: '',
    }
  },
  methods: {
    getWord() {
      axios.get('https://api.wordnik.com/v4/words.json/randomWord', {
          params: {
            api_key: 'XXXXXXXXXX',
            hasDictionaryDef: true,
            minCorpusCount: 4
          }
        })
        .then(function (response) {
          console.log(response.data.word);
          this.randomWord = response.data.word;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
  },
}
</script>

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    简单的回答:我应该在第一个承诺中使用箭头函数。

    变化:

    .then(function (response) {
              console.log(response.data.word);
              this.randomWord = response.data.word;
            })
    

    到:

    .then((response) => {
              this.randomWord = response.data.word;
            })
    

    可以在这里找到更好的解释:Vue - Cannot set property of undefined in promise

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2020-10-23
      • 1970-01-01
      • 2018-02-12
      相关资源
      最近更新 更多