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

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

是vue3的项目吗

看着没啥问题,你main.js使用了条件编译,可以检查一下HBuilderX的vue版本,是否为2.0

打印this 看看 ,main.js 里打印一下request看看 。vue3的话 不是这样用的

import { ref } from 'vue'
import { request } from '@/utils/request'
export default {
  setup() {
    const data = ref(null)
    const $request = request.bind(this)
    const fetchData = async () => {
      data.value = await $request('url', { method: 'GET' })
    }
    return {
      data,
      fetchData
    }
  }
}