鍍金池/ 問答/HTML/ vue中外部js文件請求數(shù)據(jù)如何再成功后把數(shù)據(jù)返給調(diào)用的組件

vue中外部js文件請求數(shù)據(jù)如何再成功后把數(shù)據(jù)返給調(diào)用的組件

這個項目是我用vue寫的項目用在微信網(wǎng)頁中,現(xiàn)在我要請求微信的位置的api然后獲得經(jīng)緯度參數(shù)然后再請求后臺接口獲得數(shù)據(jù),我寫在每個組件中是沒問題的,現(xiàn)在我想把這個方法提出來做個公共方法來用,可是我先方法可以調(diào)用也能請求到數(shù)據(jù),但是我在調(diào)用方法的組件中拿不到數(shù)據(jù),下面是代碼,寫在一個單獨的js文件中

//地理位置定位
import {getLocationUrl} from 'common/config'
import {SaveLocalStorage,GetLocalStorage} from 'common/localStorage'
import {PasswordPost} from 'common/tool'
export function GetLocationPos(){
    let _this=this
    return wx.ready(function(){
            wx.getLocation({
            type: 'wgs84', // 默認(rèn)為wgs84的gps坐標(biāo),如果要返回直接給openLocation用的火星坐標(biāo),可傳入'gcj02'
            success: function (res) {
                 let data=JSON.stringify(res)
                 SaveLocalStorage('_User_Loaction_',data)
                 let str=res.latitude+','+res.longitude
                return SendLocationAjax(str)
            }
        })
     })
}
function SendLocationAjax(params){
            //獲取詳細(xì)的城市信息
        return vm.$http.post(getLocationUrl,PasswordPost({location:params})).then((res)=>{
            // console.log(res.data)
            let data=JSON.stringify(res.data.data)
            vm.$cookie.set('user_location_info',data,{ expires: '1h' })//存一個1小時的地理cookie
            console.log(JSON.parse(vm.$cookie.get('user_location_info')))
            return res.data
        })
}

問下該如何修改可以在組件中拿到數(shù)據(jù)

回答
編輯回答
離殤

GetLocationPos這個函數(shù)直接調(diào)用能返回數(shù)據(jù)么?
wx.ready的回調(diào)函數(shù)函數(shù)沒有定義return返回值,返回的應(yīng)該是undefined吧

2017年6月20日 21:52
編輯回答
九年囚

傳一個回調(diào)函數(shù)進(jìn)去

2017年11月15日 10:57
編輯回答
夏夕

在你需要這組數(shù)據(jù)的組件中, 引用你這個外部獲取地理位置的 js 文件

import {GetLocationPos} from 'js 文件路徑'
import {SendLocationAjax} from 'js 文件路徑'

接下來只需在你的生命周期里面調(diào)用這兩個方法,就能獲取到你return 出來的值

2018年5月9日 16:37