一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第2天,点击查看活动详情。
入手
一、导入已有git
项目的操作流程
- 安装
git
插件,导入git
项目 - 导入的项目若没有安装
uni-ui
,需要自己手动安装一遍,安装地址 - 新导入的项目,初始化可能没有识别为小程序项目,需要右键跑下重新识别项目类型
- 打开你的微信开发者工具,在设置 - 安全设置 - 安全 - 开启服务端端口(若无开启,运行时会报错)
- 完成以上配置后,点击运行到微信开发者工具即可~
二、着手搭建框架
1、项目简介
选用uni-app
搭建的基于vue2
的多端项目,使用uni
内置的组件和api
(uni-ui
)、sass
。
2、请求封装
使用promise
以及uni
的request
方法来封装http
请求,封装方法如下:
import config from '../config';
const baseURL = config.hostMap[config.mode] + '/service';
const app = getApp();
try {
var userInfo = wx.getStorageSync('userInfo');
var sessionId = userInfo?.sessionKey || '';
} catch(e) {}
const header = {
'content-type': 'application/json;charset=UTF-8',
'client': 'wechatapp',
'auth_type': 'sid',
'user_type': 'user',
'authorization': 'Uyv5NG9zq1qds7VP',
'userKey': 'param:key:loginInfo:' + sessionId || ''
}
export function api(url, method, data, option) {
return new Promise((resolve, reject)=>{
uni.showLoading({
title: '加载中',
mask: true
})
uni.request({
url: baseURL + url,
timeout: option?.timeout || 3000,
method: method || 'GET',
header: {...header, ...option?.header},
data: data || {},
success: function(response) {
uni.hideLoading();
if(response.data.code != 0) {
uni.showToast('请求异常');
return resolve(response.data)
} else {
return resolve(response.data.data)
}
},
fail: function(error) {
uni.showToast('请求异常');
return reject(error)
}
})
})
}
export {
baseURL
}
具体调用方法,页面中的调用可用Promise
then/catch
来调用,也可用 async/await
来调用
import { api } from '../utils/service/request'
// 获取地区服务商列表
export const getCompanyList = (() => {
return api("/user/company/p_list")
})
3、全局注入$globalData
方法上借鉴了网上查询到一些资料,通过在app.vue
中重新定义App
、Page
、Component
生命周期,在原来生命周期钩子中,再另外全局加上代码块。关键代码如下:
三、开发注意事项
- 除了可使用
uni-app
封装的api
方法,微信专用的api
(如微信运动、卡券等)一样可以使用 - 有一些写法有改动,如:
wx:for="{{list}}" wx:key="key"
应改为v-for="(item, index) in list"
,即所有微信小程序wxml
表达式的写法都转为vue
的写法 - 路由的配置信息需要在
pages.json
中配置,同样也支持分包配置,分包通过subPackages
配置;路由的配置项有分为path
路径和style
样式的设置,style
的设置同原生差不多,同样可以设置导航栏背景色,导航栏文字颜色,禁止页面滚动等操作~