一、遇到问题:
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>
三、运行结果和报错内容:
求热心朋友帮忙解答,是哪里除了问题,非常感谢!