在axios.get请求到的值怎么在外部使用?

问题描述

在axios.get方法的外部使用内部定义的变量值时出错。
ipAddress的值是当前ip所在的国家代码,我希望能从get方法外部取到这个值。
试过定义一个变量将axios.get方法整个赋值给它,但是这样得到的是一个promise对象。
用全局变量也没有成功,不知道是不是自己代码写错了

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

下面代码得到的是promise变量
var getIP = axios.get('http://ip-api.com/json').then(function (response) {
    var ipAddress = response.data.countryCode
    console.log(ipAddress)
}).catch(function (error) {
  console.log(error)
})
console.log(getIP)

全局变量代码
App.vue文件中:
<script>
    export default {
      name: 'App',
      created: function () {
      },
      ipAddress: ''
    }
</script>

event.vue文件中:
import _global from '../App.vue'created: function () {
    Vue.prototype.GLOBAL = _global
    axios.get('http://ip-api.com/json').then(function (response) {
      _global.ipAddress = response.data.countryCode
    }).catch(function (error) {
      console.log(error)
    })
    console.log(this.GLOBAL.ipAddress)
}

使用全局变量方法时console.log(this.GLOBAL.ipAddress)的值还是App.vue中ipAddress的空值,但是每次我改变App.vue中ipAddress值的时候,控制台会输出一次正确的值,之后输出的都是改变的那个值。求指点 = =||


幕布斯7119047
浏览 2885回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Vue.js