uni-app简易教程

使用uni-app制作app和小程序(基础)

提前了解的知识:
html5:H5基础教程
css3:css3基础教程
javaScript:js基础教程
vue:vue教程
需要安装的环境/工具:
node.js:node.js安装教程
HbuilderX:官方下载链接
可能会使用的插件:
uView:基于uni-app的UI框架
uChart:基于uni-app的图表
ColorUI:UI框架(可选用)
uni-ui:官方推出的扩展UI框架(可选用)

1.创建项目

在这里插入图片描述

1.1项目目录结构

在这里插入图片描述

2 项目运行

2.1浏览器运行

在这里插入图片描述

2.2模拟器运行

在这里插入图片描述

2.3微信开发者工具运行

在这里插入图片描述
注意:如果是第一次使用,需要先配置小程序ide的相关路径,同时,在小程序的设置->安全中打开服务端口才可以正常运行
在这里插入图片描述

3.项目发布

以打包APP为例:
在这里插入图片描述
出现以下界面,点击打包
在这里插入图片描述

4.注意事项`

4.1尺寸单位

uni-app 支持的通用 css 单位包括 px、rpx

px 即屏幕像素
rpx 即响应式px,一种根据屏幕宽度自适应的动态单位。以750宽的屏幕为基准,750rpx恰好为屏幕宽度。屏幕变宽,rpx 实际显示效果会等比放大。
注意 rpx 是和宽度相关的单位,屏幕越宽,该值实际像素越大。如不想根据屏幕宽度缩放,则应该使用 px 单位。
如果开发者在字体或高度中也使用了 rpx ,那么需注意这样的写法意味着随着屏幕变宽,字体会变大、高度会变大。如果你需要固定高度,则应该使用 px 。
rpx不支持动态横竖屏切换计算,使用rpx建议锁定屏幕方向
链接: link.

4.2与H5的差异

标签差异

  1. div 改成 view
  2. span、font 改成 text
  3. a 改成 navigator
  4. img 改成 image
  5. select 改成 picker
  6. iframe 改成 web-view
  7. ul、li没有了,都用view替代
  8. 区域滚动使用scroll-view,不再使用div的区域滚动处理方式
  9. 左右、上下滑动切换,有专门的swiper组件,不要使用div模拟

js差异 :
1.ajax 改成 uni.request。
2.cookie、session.storage 没有了,改用 uni.storage ;3.local.storage 也改成 uni.storage。
4.alert,confirm 改成 uni.showmodel
5.window的resize 改为了 uni.onWindowResize

此处只列举常见差异,更多详细差异请查询官方文档

4.3页面配置

页面若想展示,则需要在page.json文件中配置相关的页面信息。

在这里插入图片描述
pages:
1.pages节点的第一项为应用入口页(即首页)
2.应用中新增/减少页面,都需要对 pages 数组进行修改
3.文件名不需要写后缀,框架会自动寻找路径下的页面资源
globalStyle:
全局样式,用于设置应用的状态栏、导航条、标题、窗口背景色等。
tabBar:
导航栏,默认为底部导航栏。
tabBar 中的 list 是一个数组,只能配置最少2个、最多5个 tab,tab 按数组的顺序排序

4.4UI框架使用(以uView为例)

建议使用npm方式安装,方便后续升级
如果项目是新创建的,根目录又没有package.json文件的话,请先进行npm初始化。
如果有package.json而没有node_modules
则先执行依赖安装

//npm初始化
npm init -y
//依赖安装
npm install
//安装uview
npm install uview-ui
//如果需要更新
npm update uview-ui

安装完成后无需import导入组件就可以直接在页面中使用组件
以form表单为例:

<u-form :model="form" ref="uForm">
	<u-form-item left-icon="account" prop="name" label-width="60rpx" style="margin-left: 80rpx;" :leftIconStyle="{color: '#000000', fontSize: '40rpx'}">
		<u-input v-model="form.name" placeholder="请输入账号" border-color="#66B1FF" input-align="center" />
	</u-form-item>
	<u-form-item left-icon="lock" prop="password" label-width="60rpx" style="margin-left: 80rpx;" :leftIconStyle="{color: '#000000', fontSize: '40rpx'}">
		<u-input v-model="form.password" type="password" :password-icon="showPass" placeholder="请输入密码" input-align="center" />
	</u-form-item>
	<u-form-item class="selTypeItem" label-width="80rpx">
		<u-input v-model="form.type" input-align="center" @click="show = true" />
		<u-action-sheet :list="actionSheetList" v-model="show" @click="actionSheetCallback"></u-action-sheet>
	</u-form-item>
</u-form>

4.6网络请求

示例:

uni.request({
	url:'http://localhost:7000/api/Login/GetTClientuser',//并非真实接口
	data:{//传递的参数
		luTel:this.form.name,
		luPwd:this.form.password,
		luType:1
	},
	method:'GET'//请求方式
	success:(res)=>{//请求成功回调函数
		if(res.data!=""){
		uni.switchTab({//页面跳转
			url:'/pages/index/index'
		})
		}else{
			this.showErrorLoginUser()
		}
	},
})

4.8路由

uni.navigateTo(OBJECT):
保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面。
uni.redirectTo(OBJECT):
关闭当前页面,跳转到应用内的某个页面。
uni.switchTab(OBJECT)
跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。

//在起始页面跳转到test.vue页面并传递参数
uni.navigateTo({
    url: 'test?id=1&name=uniapp'
});

4.9数据缓存

uni.setStorage(OBJECT)
将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
uni.setStorageSync(KEY,DATA)
将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
uni.getStorage(OBJECT)
从本地缓存中异步获取指定 key 对应的内容。
uni.getStorageSync(KEY)
从本地缓存中同步获取指定 key 对应的内容。

uni.setStorageSync('PTid', this.PTid);
const value = uni.getStorageSync('ptid');
if (value) {
	console.log(value);
}

4.10网络请求封装

在这里插入图片描述
config.js文件中存放基础配置信息,如ip地址,端口号

const requestURL = 'http://localhost:7000/'
export { requestURL}

request.js中使用promise封装uni.request

import { requestURL } from './config'
export const myRequest = (option)=>{
	return new Promise((resolve, reject) => {
		uni.request({
			url: requestURL + option.url,
			method:option.method||'GET',
			data:option.data||{},
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				
				reject(err)
			}
		})
	}).catch(err => console.log(err))
}

api中封装接口信息

import {
	myRequest
} from '../util/request.js'
export default {
	userLogin(luTel, luPwd, luType) {
		return myRequest({
			url: 'api/Login/GetTClientuser',
			method: 'GET',
			data: {
				luTel,
				luPwd,
				luType
			}
		})
	}
}

调用时:import loginApi from '../../common/api/loginApi.js'

loginApi.userLogin(this.form.name, this.form.password, this.PTid).then(res => {
	if (res.data != "") {
		uni.setStorageSync('PTid', this.PTid);
		uni.switchTab({
			url: '/pages/index/index'
		})
	} else {
		this.showErrorLoginUser()
	}
})

4.11使用uChart

在这里插入图片描述
1.引入import uCharts from '../../js_sdk/u-charts/u-charts/u-charts.js'
2.模板写法<canvas canvas-id="canvasLineA" id="canvasLineA" class="charts" @touchstart="touchLineA"></canvas>
3.实例化canvaLineA=new uCharts
代码示例:可参照官方文档

<template>
	<view class="qiun-columns">
		<view class="qiun-bg-white qiun-title-bar qiun-common-mt" >
			<view class="qiun-title-dot-light">基本折线图</view>
		</view>
		<view class="qiun-charts" >
			<canvas canvas-id="canvasLineA" id="canvasLineA" class="charts" @touchstart="touchLineA"></canvas>
		</view>
	</view>
</template>

<script>
	import uCharts from '../../js_sdk/u-charts/u-charts/u-charts.js'
	var _self;
	var canvaLineA=null;
	export default {
		data() {
			return {
				cWidth:'',
				cHeight:'',
				pixelRatio:1,
			}
		},
		onLoad() {
			_self = this;
			this.cWidth=uni.upx2px(750);
			this.cHeight=uni.upx2px(500);
			this.getServerData();
		},
		methods: {
			getServerData(){
				uni.request({
					url: 'http://localhost:7000/api/HistorySearch/GetPingTaiYGPOWERTJByDay',
					data: {
						pingTaiCode: 1,
						dt: '2020/7/19 10:59:59'
					},
					success: function(res) {
						let LineA = {
							categories: [],
							series: [{
								name: '电能',
								data: []
							}]
						};
						for (var i = 0; i < res.data.length; i++) {
							LineA.categories.push(res.data[i].h + '时')
							LineA.series[0].data.push(res.data[i].v)
						}
						console.log(LineA)
						_self.showLineA("canvasLineA", LineA);
					},
					fail: () => {
						_self.tips="网络错误,小程序端请检查合法域名";
					},
				});
			},
			showLineA(canvasId,chartData){
				canvaLineA=new uCharts({
					$this:_self,
					canvasId: canvasId,
					type: 'line',
					fontSize:11,
					legend:{show:true},
					dataLabel:false,
					dataPointShape:true,
					background:'#FFFFFF',
					pixelRatio:_self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: true,
					xAxis: {
						type:'grid',
						gridColor:'#CCCCCC',
						gridType:'dash',
						dashLength:8
					},
					yAxis: {
						gridType:'dash',
						gridColor:'#CCCCCC',
						dashLength:8,
						splitNumber:5,
						min:10,
						max:180,
						// format:(val)=>{return val.toFixed(0)+'元'}
					},
					width: _self.cWidth*_self.pixelRatio,
					height: _self.cHeight*_self.pixelRatio,
					extra: {
						line:{
							type: 'straight'
						}
					}
				});
				
			},
			touchLineA(e) {
				canvaLineA.showToolTip(e, {
					format: function (item, category) {
						return category + ' ' + item.name + ':' + item.data 
					}
				});
			}
		}
	}
</script>

<style  lang="less">
	/*样式的width和height一定要与定义的cWidth和cHeight相对应*/
	.qiun-charts {
		width: 750rpx;
		height: 500rpx;
		background-color: #FFFFFF;
		.charts {
			width: 750rpx;
			height: 500rpx;
			background-color: #FFFFFF;
		}
	}
	

</style>

4.12组件使用

组件使用方法与vue中组件方法一致
在这里插入图片描述
components中存放组件
组件导入import lineChart from '../../components/lineChart.vue'
组件注册:

components:{
			lineChart:lineChart
		}

组件使用:

<view class="chartDemo">
	<lineChart></lineChart>
</view>

4.13vuex状态管理

在这里插入图片描述
uni-app程序中内置了vuex只需要引入使用就可以
在store目录下创建index.js文件
index.js中定义公共数据及方法函数。并将它导出

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		currentSbId: null,
		userHomeCompanyId: null,
	},
	mutations: {
		changeUserHomeCompanyId(state, companyId) {
			state.userHomeCompanyId = companyId
		},
		changeCurrentSbId(state, sbId) {
			state.currentSbId = sbId;
		}
	}

})
export default store

在main.js中挂载

import Vue from 'vue'
import App from './App'
import uView from "uview-ui"
import store from './store'
Vue.config.productionTip = false
Vue.use(uView);
App.mpType = 'app'
Vue.prototype.$store=store
const app = new Vue({
    ...App,
	store
})
app.$mount()

在页面中使用

<script>
	export default{
		onLoad() {
			console.log(this.$store)
		}
	}
</script>

猜你喜欢

转载自blog.csdn.net/qq_42131193/article/details/107482460