vue中外部js文件请求数据如何再成功后把数据返给调用的组件

这个项目是我用vue写的项目用在微信网页中,现在我要请求微信的位置的api然后获得经纬度参数然后再请求后台接口获得数据,我写在每个组件中是没问题的,现在我想把这个方法提出来做个公共方法来用,可是我先方法可以调用也能请求到数据,但是我在调用方法的组件中拿不到数据,下面是代码,写在一个单独的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', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'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){
            //获取详细的城市信息
        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
        })
}

问下该如何修改可以在组件中拿到数据

阅读 7.3k
3 个回答

在你需要这组数据的组件中, 引用你这个外部获取地理位置的 js 文件

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

接下来只需在你的生命周期里面调用这两个方法,就能获取到你return 出来的值

传一个回调函数进去

GetLocationPos这个函数直接调用能返回数据么?
wx.ready的回调函数函数没有定义return返回值,返回的应该是undefined吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题