javascript - 如何在 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)
},
解决方案
共享数据道具
正如@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_student
。console.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)
推荐阅读
- corda - Corda 中的帐户保险库查询
- java - Java PreparedStatement executeBatch 方法抛出主键的唯一约束
- r - 在 R 中使用 ggplot2 进行函数式编程 - NSE
- python - pyautogui.screenshot() 捕获的放大/缩小图像
- python - 如何在包含相同字符的字符串中按索引替换字符
- android-studio - 到达断点时将断开调试模式
- c++ - 空子对象优化
- rust - 如何在 Rust 中操作二进制数?
- algorithm - 公差标准 Brent 方法
- dart - dart DateTime.add 从特定日期开始添加 1 小时