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

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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵