問題描述在axios.get方法的外部使用內(nèi)部定義的變量值時出錯。ipAddress的值是當(dāng)前ip所在的國家代碼,我希望能從get方法外部取到這個值。試過定義一個變量將axios.get方法整個賦值給它,但是這樣得到的是一個promise對象。用全局變量也沒有成功,不知道是不是自己代碼寫錯了相關(guān)代碼// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)下面代碼得到的是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值的時候,控制臺會輸出一次正確的值,之后輸出的都是改變的那個值。求指點 = =||
在axios.get請求到的值怎么在外部使用?
幕布斯7119047
2018-08-26 15:05:56