慧羽网络 2023-04-18 17:22 采纳率: 100%
浏览 114
已结题

uniapp封装request方法调用报错:TypeError: this.$request is not a function

一、遇到问题:

uniapp封装request方法调用报错:TypeError: this.$request is not a function

二、代码片段

1、request.js

const BASE_URL = 'http://127.0.0.1:8000'
const header = {
    Authorization: uni.getStorageSync('token')
}
export const request = (
    url = '',
    method = 'GET',
    data = {},
) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + url,
            header: header,
            method: method,
            data: data,
            dataType: 'JSON'
        }).then((response) => {
            setTimeout(function() {
                uni.hideLoading()
            }, 200)
            let [error, res] = response
            resolve(res.data)
        }).catch(error => {
            let [err, res] = error
            reject(err)
        })
    })
}

2、main.js

import App from './App'

// #ifndef VUE3
import Vue from 'vue'

import {
    request
} from './utils/request.js' // request请求接口

// 定义全局
Vue.prototype.$request = request

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import {
    createSSRApp
} from 'vue'
export function createApp() {
    const app = createSSRApp(App)
    return {
        app
    }
}
// #endif

3、页面使用

<template>
    <view>
        <button @click="getSms">打开弹窗</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {

            }
        },
        methods: {
            getSms() {
                this.$request('/sendSms', 'POST', {}).then(res => {
                    console.log(res)
                })
            }
        }
    }
</script>

<style lang="scss" scoped>

</style>

三、运行结果和报错内容:

img

求热心朋友帮忙解答,是哪里除了问题,非常感谢!

  • 写回答

3条回答 默认 最新

  • 简效 2023-04-18 17:34
    关注

    是vue3的项目吗

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月29日
  • 已采纳回答 4月21日
  • 修改了问题 4月18日
  • 创建了问题 4月18日

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么