uniapp 封装接口并使用-基础版

1.在utils文件夹下新建 api.js 和 httpRequest.js 页面

httpRequest.js:

getApp().globalData.baseUrl = 'https://xxxxxx';
import api from "@/utils/api.js";
module.exports = {
    httpRequest(url, method, param) {
        var data = param.data;
        var headerParam = {}
        if (url.indexOf("/loginApp") != -1 ) { // 根据自身项目内容 再具体判断
            headerParam = {}
        } else {
            headerParam = {
                'Authorization': token != '' ? uni.getStorageSync('token') : '', //检查缓存中有没有token 
                'Content-Type': 'application/json;charset=utf-8'
            }
        } 
        let promise = new Promise(function(resolve, reject) {
            uni.request({
                url: getApp().globalData.baseUrl + url,
                data: data,
                method: method,
                header: headerParam,
                complete: (res) => { //请求完成 
                    uni.hideLoading(); //隐藏加载
                },
                success: (res) => {
                    if (res.data.code == 200) {
                        resolve(res.data);
                    } else if (res.data.code === 401) {
                        reject(res.data.code);
                    } else {
                        uni.showToast({
                            title: res.data.msg,
                            icon: 'none'
                        });
                        reject(res.data.code);
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
        return promise;
    }
}

api.js

// 在这里面定义所有接口 
import { httpRequest } from './httpRequest';

// get请求--不带参数
function getApi(data) { 
    return httpRequest('/api', 'get', data)
}
// get请求--带参数
function getApi(data) {
    return httpRequest('/api/' + data, 'get', data)
}
// post请求--不带参数
function getApi(data) { 
    return httpRequest('/api', 'post', data)
}
// put请求--不带参数
function getApi(data) { 
    return httpRequest('/api', 'put', data)
}


export default {
     // 暴露接口   接口名
    getApi,
    ......
  }

页面调用

<script>
	import api from "@/utils/api.js";
	export default {
		data() {
			return {
				list: []
			}
		},
		methods: {
			getIndexNav() {
				// var param='' // 不传参
				var param = {
					id: ''
				}
				api.getApi(param).then(res => {
					this.list = res.data;
				})
			},
		}
	}
</script>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在uniapp封装WebSocket并全局使用,可以按照以下步骤操作: 1. 创建一个WebSocket.js文件,用于封装WebSocket的相关逻辑。在该文件中,可以定义WebSocket的连接、发送和关闭等方法。 ``` export default { socketTask: null, // 连接websocket connect(url) { this.socketTask = uni.connectSocket({ url: url, success: () => { console.log('WebSocket连接成功') } }) this.socketTask.onOpen(() => { console.log('WebSocket连接打开') }) this.socketTask.onMessage((res) => { console.log('WebSocket收到消息', res) }) this.socketTask.onError((res) => { console.log('WebSocket连接错误', res) }) this.socketTask.onClose((res) => { console.log('WebSocket连接关闭', res) }) }, // 发送消息 send(msg) { this.socketTask.send({ data: msg, success: () => { console.log('WebSocket发送消息成功', msg) } }) }, // 关闭连接 close() { this.socketTask.close({ success: () => { console.log('WebSocket连接关闭成功') } }) } } ``` 2. 在main.js中引入WebSocket.js,并将其挂载到Vue原型上,以便在全局使用。 ``` import Vue from 'vue' import App from './App' import WebSocket from './WebSocket' Vue.prototype.$socket = WebSocket Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() ``` 3. 在需要使用WebSocket的页面或组件中,可以通过this.$socket来用WebSocket的连接、发送和关闭等方法。 ``` export default { created() { this.$socket.connect('ws://localhost:8080') this.$socket.send('Hello, WebSocket!') }, beforeDestroy() { this.$socket.close() } } ``` 这样,我们就可以在uniapp封装WebSocket并全局使用了。需要注意的是,WebSocket的连接地址应该根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值