uniapp封装全局方法
时间: 2023-05-30 20:07:34 浏览: 400
Uniapp封装全局方法的步骤如下:
1. 在uniapp项目中创建一个js文件,命名为global.js,用于存放全局方法。
2. 在global.js中定义需要封装的全局方法,例如:
```javascript
// global.js
export default {
showToast: function(title) {
uni.showToast({
title: title,
icon: 'none'
})
}
}
```
3. 在main.js中引入global.js,并将其挂载到Vue原型上:
```javascript
// main.js
import global from './global.js'
Vue.prototype.$global = global
```
4. 在其他组件中可以直接使用全局方法,例如:
```javascript
this.$global.showToast('Hello, world!')
```
这样就可以在任何组件中调用全局方法了。
相关问题
uniapp封装全局uni.request
如果你想要在 uni-app 中封装全局的 uni.request,可以按照以下步骤进行:
1. 创建一个封装文件,并在其中引入 uni.request:
```
import uniRequest from '@/utils/uniRequest.js'
const request = (url, method, data) => {
return uniRequest({
url: url,
method: method,
data: data
}).then(res => {
// 返回数据处理
return res.data
}).catch((err) => {
// 错误处理
console.log(err)
})
}
export default request
```
2. 在 main.js 中将封装好的 request 方法挂载到 Vue 实例上,使其成为全局可用的方法:
```
import Vue from 'vue'
import App from './App'
import request from '@/api/request.js'
Vue.config.productionTip = false
// 全局挂载request方法
Vue.prototype.$request = request
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
```
3. 在需要使用网络请求的地方,直接通过 this.$request() 调用即可:
```
export default {
data() {
return {
list: []
}
},
created() {
this.getList()
},
methods: {
getList() {
this.$request('/api/getList', 'get', {}).then(res => {
console.log(res)
this.list = res
})
}
}
}
```
这样就可以在任何组件中方便地使用全局封装的 uni.request 进行网络请求了。
uniapp 封装websocket 全局引用
在uniapp中封装websocket并实现全局引用,可以按照以下步骤进行:
1. 在uniapp项目的common目录下创建一个websocket.js文件,用于封装websocket:
```javascript
export default {
socket: null,
init(url) {
this.socket = new WebSocket(url);
this.socket.onopen = this.onopen;
this.socket.onmessage = this.onmessage;
this.socket.onclose = this.onclose;
this.socket.onerror = this.onerror;
},
onopen() {
console.log("websocket连接成功");
},
onmessage(event) {
console.log("收到消息:", event.data);
},
onclose() {
console.log("websocket连接关闭");
},
onerror() {
console.log("websocket连接错误");
},
send(data) {
if (this.socket && this.socket.readyState === 1) {
this.socket.send(data);
}
},
close() {
if (this.socket) {
this.socket.close();
}
}
};
```
2. 在uniapp项目的main.js文件中全局引用websocket.js:
```javascript
import websocket from "@/common/websocket.js";
Vue.prototype.$websocket = websocket;
```
3. 在需要使用websocket的页面中,先通过this.$websocket.init(url)方法初始化websocket连接,然后即可使用this.$websocket.send(data)方法发送消息,收到消息后会自动触发this.$websocket.onmessage回调函数。
```javascript
export default {
mounted() {
this.$websocket.init("ws://localhost:8080");
},
methods: {
sendMessage() {
this.$websocket.send("hello world");
}
}
};
```