0%

uniapp的跨端效果演示

uniapp 的跨端效果演示

公司使用 uniapp 开发项目的时候,会优先对标考虑某个平台,在开发阶段,优先测试该平台。
多测试兼容性较差的平台(微信小程序)

  1. web 端
  2. 小程序端
    • HbuilderX 工具—设置—-运行设置
    • 微信开发者工具 设置—-安全设置—-服务端口(打开)
    • HB 上面一键发行小程序
  3. App 端
  4. App 真机测试

自定义组件封装

跟 Vue 中封装组件一样,引入、挂载、使用的方式,也一样

  1. 组件与页面的生命周期有差异

    • 页面
      • onMounted 可用 Vue3 的生命周期
      • onLoad 可用小程序的生命周期 【建议使用这个】
    • 公共组件
      • onMounted 可用 Vue3 的生命周期 【建议使用这个】
  2. uniapp 的 setup 中使用 onLoad

    1
    import {onLoad} from '@dcloudio/uni-app'

数据请求方式

方法 1:使用 uni.request

1
2
3
4
5
6
7
8
9
10
11
12
uni.request({
url: "https://woniu.h5project.cn/1.1/classes/Job",
method: "GET",
header: {
"X-LC-Id": "自己的id",
"X-LC-Key": "自己的key",
"Content-Type": "application/json",
},
success: (res) => {
console.log(res);
},
});

方法 2:自行封装 uni.request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// promise的三种状态: pendding处理中  resolve成功   reject失败

import { BASE_URL, ID, KEY } from "../config/index.js";

function http({ url, method = "GET", data = {} }) {
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + url,
method,
data,
header: {
"X-LC-Id": ID, //此处必须使用自己的ID
"X-LC-Key": KEY, //此处必须使用自己的Key
"Content-Type": "application/json",
},
success: (res) => {
resolve(res); //交给then
},
fail: (err) => {
reject(err); //交给catch
},
});
});
}

function get(url, data) {
return http({ url, method: "GET", data });
}

function post(url, data) {
return http({ url, method: "POST", data });
}

function del(url, data) {
return http({ url, method: "DELETE", data });
}

export { http, get, post, del };

方法 3:使用 luch-request 第三方库

luch-request - DCloud 插件市场

3.x 文档 | luch-request (quanzhan.co)

axios 可能不兼容小程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import Request from "../js_sdk/luch-request/luch-request/index.js";
import { BASE, ID, KEY } from "../config/index.js";
const http = new Request();
/* config 为默认全局配置*/
http.setConfig((config) => {
config.baseURL = BASE + "/1.1/"; /* 根域名 */
config.header = {
"X-LC-Id": ID,
"X-LC-Key": KEY,
"Content-Type": "application/json",
};
return config;
});
// 请求拦截器
http.interceptors.request.use(
(config) => {
// 可使用async await 做异步操作
config.header = {
...config.header,
// a: 1 // 演示拦截器header加参
};
console.log("请求拦截器");
return config;
},
(config) => {
// 可使用async await 做异步操作
return Promise.reject(config);
}
);
//响应拦截器
http.interceptors.response.use(
(response) => {
/* 对响应成功做点什么 可使用async await 做异步操作*/
console.log("响应拦截器", response);
return response;
},
(response) => {
/* 对响应错误做点什么 (statusCode !== 200)*/
console.log(response);
return Promise.reject(response);
}
);

export default http;

任务

  1. 在项目中完成某个结构的组件封装
  2. 在项目中发异步请求,尝试使用 luch-request
  3. 体验各个平台的发布流程
赏包辣条吃吧