初试uni-app框架

116 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第2天,点击查看活动详情

入手

一、导入已有git项目的操作流程

  1. 安装git插件,导入git项目
  2. 导入的项目若没有安装uni-ui,需要自己手动安装一遍,安装地址
  3. 新导入的项目,初始化可能没有识别为小程序项目,需要右键跑下重新识别项目类型
  4. 打开你的微信开发者工具,在设置 - 安全设置 - 安全 - 开启服务端端口(若无开启,运行时会报错) image.png
  5. 完成以上配置后,点击运行到微信开发者工具即可~

二、着手搭建框架

1、项目简介

选用uni-app搭建的基于vue2的多端项目,使用uni内置的组件和api(uni-ui)、sass

2、请求封装

使用promise以及unirequest方法来封装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中重新定义AppPageComponent生命周期,在原来生命周期钩子中,再另外全局加上代码块。关键代码如下:

三、开发注意事项

  1. 除了可使用uni-app封装的api方法,微信专用的api(如微信运动、卡券等)一样可以使用
  2. 有一些写法有改动,如:wx:for="{{list}}" wx:key="key" 应改为 v-for="(item, index) in list",即所有微信小程序wxml表达式的写法都转为vue的写法
  3. 路由的配置信息需要在pages.json中配置,同样也支持分包配置,分包通过subPackages配置;路由的配置项有分为path路径和style样式的设置,style的设置同原生差不多,同样可以设置导航栏背景色,导航栏文字颜色,禁止页面滚动等操作~