首页 > 解决方案 > 如何在 axios 请愿书之前显示一个变量

问题描述

我正在发出一个获取请求,将结果保存在一个名为 name_student 的变量中。如何在其他方法中显示此变量?或者我应该如何申报?

这是我的代码:

getStudent(){
  axios.get('https://backunizoom.herokuapp.com/student/2')
        .then((result) => {
          console.log(result.data)
        this.name_student=result.data.name
        console.log(name_student)
        
    })
    console.log(name_student)
},

标签: javascriptvue.js

解决方案


共享数据道具

正如@scar-2018 在评论中所建议的那样,您只需将其声明name_student为数据道具,以使该道具可用于所有组件方法和钩子:

export default {
  data() {
    return {
      name_student: '',
    }
  },
  methods: {
    getStudent() {
      axios.get(/*...*).then((result) => {
        this.name_student = result.data.name

        this.updateStudentName()
      })
    },
    updateStudentName() {
      this.name_student += ' (student)'
    }
  }
}

访问异步数据

评论说您在undefined登录时看到name_studentconsole.log()假设您问题中的代码在调用位置方面没有拼写错误,则axios回调是异步运行的,并且您在修改它this.name_student 之前正在记录: axios

axios.get(/*...*/).then((result) => {
  this.name_student = result.data.name
  console.log(this.name_student) // => 'foo' ✅
})

console.log(this.name_student) // => undefined ❌ (not yet set)

推荐阅读