前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >『UniApp』核心语法

『UniApp』核心语法

原创
作者头像
BNTang
修改2024-01-16 21:15:09
2032
修改2024-01-16 21:15:09
举报

Uni-App 简介

框架介绍

  • uni,读 you ni,是统一的意思
  • Uni-app 是 Dcloud 公司的产品,是一个跨端开发框架,基于 vue.js 技术栈,被用于移动端开发
  • 用 Uni-App 编写一套代码,可发布到 iOSAndroidWeb(响应式)以及各种小程序(微信 / 支付宝 / 百度 / 头条 / QQ / 钉钉 / 淘宝)应用等多个平台

框架生态

  • DCloud 公司拥有 800 万开发者、数百万应用、12 亿手机端月活用户、数千款 Uni-app 插件、70+微信 / qq群
  • Uni-app 在开发者数量、案例、跨端抹平度、扩展灵活性、性能体验、周边生态、学习成本、开发成本等 8 大关键指标上拥有更强的优势

详细数据:

源码地址

源码自行去 git 搜索 uniapp,这里不过多赘述。

框架分析

Uni-App 功能架构图:

Uni-App 功能总结:

  • Uni-app 底层集成了 native 技术,就是 h5+引擎,能调用手机原生 api,所以 Uni-app 能开发接近原生性能的 app,这是 js 引擎部分
  • Uni-app 底层集成的是双引擎,除了 js 引擎以外,还有一个独立的渲染引擎

nvue 渲染:

  • nvue 内部集成了 weex
  • 用于原生 iOS 和 Android 端渲染

webview 渲染:

  • 基于 webkit 内核
  • 用于网页端渲染

Uni-App 环境搭建

安装 hbuilderX

  • hbuilderx 也是 dcloud 公司出品的 ide 产品
  • 用 Uni-app 开发跨多端产品,实现一次开发,多端发布就必须用 hbuilderx 这个神器 IDE

下载地址:https://www.dcloud.io/hbuilderx.html

安装夜神模拟器

  • 开发 app,就少不了连机调试,你可以连接手机调试,也可以安装一个模拟器
  • 下载地址:https://www.yeshen.com/

下载之后无脑下一步,然后安装完毕之后直接运行即可如下:

配置环境

hbuilderx 连接到模拟器,选择工具 → 设置,打开配置界面,选择运行配置,如下图:

细节概要,adb 路径选择模拟器安装包的 adb.exe 地址,模拟器端口,夜神模拟器默认是 62001

插件市场插件安装

插件市场的插件主要有组件类和编译类两大类:

组件类:

  • 点击安装后会直接安装到当前打开的 Uni-app 项目中,而且是指定的文件夹 components

编译类:

  • 类似于 webpack 的 loader,这个是放在 hbx 的安装包里

安装常用的插件

Uni-App 快速入门

框架简介

  • Uni-app 使用 vue 的语法 + 小程序的标签和 API

核心技术点

环境配置

新建 Uni-app 空模板项目:

开发规范:

资源路径说明:

模板内引入静态资源

template 内引入静态资源,如 image、video 等标签的 src 属性时,可以使用 相对路径 或者 绝对路径,形式如下:

注意事项@ 开头的绝对路径以及相对路径会经过 base64 转换规则校验,引入的静态资源在非 h5 平台,均不转为 base64,H5 平台,小于 4kb 的资源会被转换成 base64,其余不转

JS 文件引入

js 文件或 script 标签内(包括 renderjs 等)引入 js 文件时,可以使用相对路径和绝对路径,形式如下图:

CSS 引入静态资源

css 文件或 style 标签内引入 css 文件时(scss、less 文件同理)可以使用相对路径或绝对路径,如下图:

多端运行

  • 文件 → 新建 → 项目

选中 App.vue

浏览器运行:运行 → 运行到浏览器 → Chrome

微信小程序运行

注意,如果是第一次使用,需要先配置小程序 ide 的相关路径,才能运行成功,微信开发者工具下载地址:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html

配置微信小程序开发工具安装包地址如下:

微信小程序 → 设置 → 安全 → 开启服务端口:

支付宝小程序运行

支付宝小程序开发工具下载地址:https://opendocs.alipay.com/mini/ide/download

无脑下一步安装即可,安装完毕之后使用 HBuilderX 进行运行,以支付宝小程序的方式进行编译如下:

真机运行

注意,打开夜神模拟器的安装文件夹,找到【debugReport.bat】文件,双击启动该批处理文件:

查看端口:62001

运行 → 运行到手机或模拟器:

目录结构分解

目录结构解释:

代码语言:tex
复制
┌─uniCloud              云空间目录,阿里云为uniCloud-aliyun,腾讯云为uniCloud-tcb(详见uniCloud)
│─components            符合vue组件规范的uni-app组件目录
│  └─comp-a.vue         可复用的a组件
├─hybrid                App端存放本地html文件的目录,详见
├─platforms             存放各平台专用页面的目录,详见
├─pages                 业务页面文件存放的目录
│  ├─index
│  │  └─index.vue       index页面
│  └─list
│     └─list.vue        list页面
├─static                存放应用引用的本地静态资源(如图片、视频等)的目录,注意:静态资源只能存放于此
├─uni_modules           存放[uni_module](/uni_modules)规范的插件。
├─wxcomponents          存放小程序组件的目录,详见
├─main.js               Vue初始化入口文件
├─App.vue               应用配置,用来配置App全局样式以及监听 应用生命周期
├─manifest.json         配置应用名称、appid、logo、版本等打包信息,详见
└─pages.json            配置页面路由、导航条、选项卡等页面类信息,详见

注意事项:

  • 编译到任意平台时,static 目录下的文件均会被完整打包进去,且不会编译。非 static 目录下的文件(vue、js、css 等)只有被引用到才会被打包编译进去
  • static 目录下的 js 文件不会被编译,如果里面有 es6 的代码,不经过转换直接运行,在手机设备上会报错
  • css、less / scss 等资源不要放在 static 目录下,建议这些公用的资源放在自建的 common 目录下
  • HbuilderX 1.9.0+ 支持在根目录创建 ext.json、sitemap.json 等小程序需要的文件

经过了如上的一番讲解之后我们接下来再次新建一个干净点的项目如下:

创建好了一个空项目之后我们主要关注的内容为 uni-app 的内容,首先来看看 pages.json 的内容 pages.json 有许多的内容,其它的配置项请参考官方文档:https://uniapp.dcloud.io/collocation/pages

我这里只介绍常用的配置,globalStyle 内容如下:

代码语言:json
复制
"globalStyle": {
	// 导航栏标题颜色及状态栏前景颜色,仅支持 black/white
	"navigationBarTextStyle": "white",
	
	// 导航栏标题文字内容
	"navigationBarTitleText": "BNTang",
	
	// 导航栏背景颜色(同状态栏背景色)
	"navigationBarBackgroundColor": "#00aa7f",
	
	// 下拉显示出来的窗口的背景色
	"backgroundColor": "#ff0000",
	
	// 是否开启下拉刷新
	"enablePullDownRefresh": true,
	
	// 下拉 loading 的样式,仅支持 dark / light
	"backgroundTextStyle": "light",
	
	// 导航栏图片地址(替换当前文字标题),支付宝小程序内必须使用https的图片链接地址
	"titleImage": "https://xiaohuihuit.github.io/images/avatar.jpg"
}

微信小程序运行效果图:

Web 端运行效果图:

底部 Tab 配置

修改 package.json 添加 pages 内容与 tabBar 新属性:

代码语言:json
复制
// pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
"pages": [{
	"path": "pages/index/index",
	"style": {
		"navigationBarTitleText": "首页",

		// 导航栏背景颜色(同状态栏背景色)
		"navigationBarBackgroundColor": "#007AFF",
		"h5": {
			"pullToRefresh": {
				"color": "#007AFF"
			},
			// 导航栏
			"titleNView": {
				"titleText": "我的"
			}
		}
	}
}, {
	"path": "pages/course/course",
	"style": {
		"navigationBarTitleText": "选课"
	}
},
{
	"path": "pages/friends/friends",
	"style": {
		"navigationBarTitleText": "朋友圈"
	}
},
{
	"path": "pages/study/study",
	"style": {
		"navigationBarTitleText": "学习"
	}
},
{
	"path": "pages/mine/mine",
	"style": {
		"navigationBarTitleText": "我的"
	}
}],
代码语言:json
复制
"tabBar": {
	"color": "#333333",
	"selectedColor": "#FF0000",
	"backgroundColor": "#d3d3d3",
	"borderStyle": "black",
	"fontSize": "14px",
	"position": "bottom",
	"list": [{
			"text": "首页",
			"pagePath": "pages/index/index",
			"iconPath": "static/tabs/home.png",
			"selectedIconPath": "static/tabs/home-selected.png"
		},
		{
			"text": "选课",
			"pagePath": "pages/course/course",
			"iconPath": "static/tabs/course.png",
			"selectedIconPath": "static/tabs/course-selected.png"
		},
		{
			"text": "朋友圈",
			"pagePath": "pages/friends/friends",
			"iconPath": "static/tabs/friends.png",
			"selectedIconPath": "static/tabs/friends-selected.png"
		},
		{
			"text": "学习",
			"pagePath": "pages/study/study",
			"iconPath": "static/tabs/study.png",
			"selectedIconPath": "static/tabs/study-selected.png"
		},
		{
			"text": "我的",
			"pagePath": "pages/mine/mine",
			"iconPath": "static/tabs/mine.png",
			"selectedIconPath": "static/tabs/mine-selected.png"
		}
	]
}

easycom 和 condition

常用组件

view

官方文档:https://uniapp.dcloud.io/component/view.html

代码语言:vue
复制
<template>
	<view class="box1" hover-class="box1-active" :hover-stay-time="2000">
		<view class="box2" hover-class="box2-active" hover-stop-propagation :hover-start-time="1000">
			BNTang
		</view>
	</view>
</template>

<script>
</script>

<style>
	.box1 {
		width: 200px;
		height: 200px;
		background-color: #FF0000;
	}

	.box1-active {
		background-color: #00FF00;
	}

	.box2 {
		width: 100px;
		height: 100px;
		background-color: #0000FF;
	}

	.box2-active {
		background-color: pink;
	}
</style>
text

官方文档:https://uniapp.dcloud.io/component/text.html

代码语言:vue
复制
<template>
	<view>
		<text selectable user-select space="nbsp" style="font-size: 14px;">日前,国务院 &nbsp; &amp; &apos; &ensp; &emsp;
			办公厅印发《关于加快发展保障性租赁住房的意见》。其中提到,大城市中的新市民、青年人等群体住房困难问题突出,将加快完善以公租房、保障性租赁住房和共有产权住房为主体的住房保障体系,尤其是加快发展保障性租赁住房。</text>
	</view>
</template>

<script>
</script>

<style>
</style>
button

官方文档:https://uniapp.dcloud.io/component/button.html

代码语言:vue
复制
<template>
	<view>
		<view id="btn">
			<button type="default">BNTang</button>
			<button type="default" size="mini">BNTang</button>
			<button type="default" size="mini" :plain="true">BNTang</button>
			<button type="default" size="mini" :plain="true" disabled>BNTang</button>
			<button type="default" loading>BNTang</button>
			<button type="primary">BNTang</button>
			<button type="warn" @click="log('https://www.cnblogs.com/BNTang')">BNTang</button>
		</view>
	</view>
</template>

<script>
	export default{
		methods: {
			log(val){
				console.log(val);
			}
		}
	}
</script>

<style>
</style>
image

官方文档:https://uniapp.dcloud.io/component/image.html

代码语言:vue
复制
<template>
	<view>
		<image :src="imgUrl" style="width: 200px; height: 200px;background-color: #4CD964;"/>
		<image :src="imgUrl" style="width: 200px; height: 200px;background-color: #4CD964;" mode="aspectFit"/>
		<image :src="imgUrl" style="width: 200px; height: 200px;background-color: #4CD964;" mode="aspectFill"/>
		<image :src="imgUrl" style="width: 200px; height: 200px;background-color: #4CD964;" mode="widthFix"/>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgUrl: 'https://avatars.githubusercontent.com/u/78400939?v=4'
			}
		}
	}
</script>

<style>
</style>

响应式单位

responsive pixel

可以根据屏幕宽度进行自适应, 规定屏幕宽为 750rpx, 如在 iPhone6 上,屏幕宽度为 375px,共有 750 个物理像素,则 750rpx = 375px = 750 物理像素,1rpx = 0.5px = 1物理像素。

换算公式
代码语言:vue
复制
<template>
	<view>
		<view class="box1">
			<text>朋友圈界面</text>
		</view>
		<view class="box2">
			<text>朋友圈界面</text>
		</view>
	</view>
</template>

<script>
</script>

<style>
	.box1 {
		width: 200px;
		height: 200px;
		background-color: red;
		font-size: 30px;
		color: #FFFFFF;
	}

	.box2 {
		margin-top: 20rpx;
		width: 400rpx;
		height: 400rpx;
		background-color: green;
		font-size: 60rpx;
		color: #FFFFFF;
	}
</style>

切换手机型号进行测试。

样式和插件使用

样式使用
  • CSS 支持的,UniApp 中都支持
代码语言:vue
复制
<template>
	<view>
		<view style="width: 300rpx; height: 300rpx; background-color: red; margin-top: 30rpx;">
			<text>BNTang</text>
		</view>
		<view class="box4">
			<text>BNTang box4</text>
		</view>
		<view class="box5">
			<text>外部样式</text>
		</view>
	</view>
</template>

<script>
</script>

<style>
	@import url("../../common/base.css");

	.box4 {
		margin-top: 20rpx;
		width: 400rpx;
		height: 400rpx;
		background-color: pink;
		font-size: 60rpx;
		color: #FFFFFF;
	}
</style>
使用字体图标

字体图标素材,自行下载,博主不提供了。

使用步骤:

  • App.vue 中引入
代码语言:vue
复制
/* 引入字体文件 */
@import url("static/fonts/iconfont.css");
  • 其它组件页面中使用
代码语言:vue
复制
<template>
	<view>
		<view class="iconfont icon-hunhetu-zhezhu" style="font-size: 300rpx; color: red;"></view>
		<view class="iconfont icon-bingtu-nandinggeer" style="font-size: 300rpx; color: red;"></view>
	</view>
</template>

<script>
</script>

<style>
</style>
插件使用
  • 比如: 安装 scss
  • 改变样式代码风格

插件市场:https://ext.dcloud.net.cn/?cat1=1&cat2=11

轮播组件

官方文档:https://uniapp.dcloud.io/component/swiper.html

常规使用
代码语言:vue
复制
<template>
	<view>
		<swiper class="swiper" :indicator-dots="true" indicator-color="rgba(0, 0, 0, .4)"
			indicator-active-color="rgba(0, 0, 0, 1)" :current="0" :autoplay="true" :interval="1000" :duration="200"
			:circular="true" vertical>
			<swiper-item>
				<view class="swiper-item" style="background-color: #55ffff;">1</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color: #ffff00;">2</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color:#ffaa00;">3</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color: #ffaaff;">4</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color: #aaff7f;">5</view>
			</swiper-item>
		</swiper>

		<swiper class="swiper" :indicator-dots="true" indicator-color="rgba(0, 0, 0, .4)"
			indicator-active-color="rgba(0, 0, 0, 1)" :current="0" :autoplay="false" :interval="1000" :duration="200"
			:circular="true" @change="change" @animationfinish="animationfinish">
			<swiper-item>
				<view class="swiper-item" style="background-color: #55ffff;">1</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color: #ffff00;">2</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color:#ffaa00;">3</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color: #ffaaff;">4</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item" style="background-color: #aaff7f;">5</view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	export default{
		methods: {
			// current 改变时会触发 change 事件
			change(event){
				console.log(event);
			},
			
			// 动画结束时会触发 animationfinish 事件
			animationfinish(event){
				console.log(event);
			}
		}
	}
</script>

<style>
</style>
定制化使用
  • 封装了一个 bntangswiper 的组件内容如下
代码语言:vue
复制
<template>
	<view class="swiper-box">
		<swiper class="swiper" :indicator-dots="false" indicator-color="rgba(0, 0, 0, .4)"
			indicator-active-color="rgba(0, 0, 0, 1)" :current="0" :autoplay="true" :interval="2000" :duration="500"
			:circular="true" @change="change">
			<swiper-item v-for="(item, index) in imgList" :key="index">
				<image class="swiper-img" :src="item.image" mode="aspectFill"></image>
				<!-- 标题 -->
				<view class="swiper-title">
					<text class="text">{{item.title}}</text>
				</view>
			</swiper-item>
		</swiper>

		<!-- 自定义指示器 -->
		<view class="swiper-dots">
			<view v-for="(item, index) in imgList" :key="index" class="indicator-dots-item"
				:class="current === index ? 'indicator-dots-crrent' : ''">
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "bntangswiper",
		props: {
			imgList: {
				type: Array,
				default: [],
				required: true
			}
		},
		data() {
			return {
				current: 0
			}
		},
		methods: {
			change(e) {
				this.current = e.detail.current;
			}
		}
	}
</script>

<style lang="scss">
	.swiper-box {
		position: relative;

		.swiper {
			width: 750rpx;
			height: 420rpx;
			max-height: 420rpx !important;
			border: 0;
			margin: 0;
			padding: 0;
			position: relative;
			right: 0;
			left: 0;

			.swiper-img {
				width: 750rpx;
				height: 100%;
			}

			.swiper-title {
				position: absolute;
				left: 0;
				bottom: 0;
				width: 750rpx;
				padding-left: 20rpx;
				padding-right: 20rpx;
				padding-top: 50rpx;
				padding-bottom: 20rpx;
				color: #FFFFFF;
				background-image: linear-gradient(transparent, rgba(0, 0, 0, .8));

				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}

		/* 指示器 */
		.swiper-dots {
			width: 750rpx;
			height: 50rpx;
			position: absolute;
			bottom: 0;
			left: 0;

			display: flex;
			justify-content: flex-end;
			align-items: center;

			.indicator-dots-item {
				width: 20rpx;
				height: 14rpx;
				background-color: rgba($color: #ffffff, $alpha: 0.5);
				margin-right: 15rpx;
				border-radius: 10rpx;
			}

			.indicator-dots-crrent {
				width: 30rpx;
				background-color: #FFFFFF;
			}
		}
	}
</style>
  • 调用, 也就是使用封装好的组件内容
代码语言:vue
复制
<template>
	<bntangswiper :imgList="list"/>
</template>

<script>
	import pic1 from '../../static/imgs/pic1.png';
	import pic2 from '../../static/imgs/pic2.png';
	import pic3 from '../../static/imgs/pic3.png';
	import pic4 from '../../static/imgs/pic4.png';

	export default {
		data() {
			return {
				list: [{
						image: pic1,
						title: '秋天是收获的季节'
					},
					{
						image: pic2,
						title: '春天是最美的颜色'
					},
					{
						image: pic3,
						title: '夕阳无限好, 只是近黄昏'
					},
					{
						image: pic4,
						title: '白雪是无尽的思念'
					}
				]
			}
		},
		methods: {}
	}
</script>

<style>
</style>

生命周期

官方文档:https://uniapp.dcloud.io/collocation/frame/lifecycle

分类
  • 应用生命周期 App.vue
代码语言:vue
复制
<script>
	export default {
		// 当uni-app 初始化完成时触发(全局只触发一次)
		onLaunch: function() {
			console.log('itlike - App Launch')
		},

		// 当 uni-app 启动,或从后台进入前台显示
		onShow: function() {
			console.log('itlike - App Show')
		},

		// 当 uni-app 从前台进入后台
		onHide: function() {
			console.log('itlike - App Hide')
		},

		// 当 uni-app 报错时触发
		onError: function(error) {
			console.log(error);
		}
	}
</script>

<style>
	/*每个页面公共css */
</style>
  • 页面生命周期
代码语言:vue
复制
// 监听页面加载,其参数为上个页面传递的数据,参数类型为 Object
onLoad(options) {
	console.log('页面加载', options);
},

onShow() {
	console.log('onShow()');
},

// 监听页面初次渲染完成
onReady() {
	console.log('onReady()');
},

onHide() {
	console.log('onHide()');
},
  • 组件生命周期 bntangswiper.vue
代码语言:vue
复制
// 组件的生命周期函数
beforeCreate() {
	console.log('beforeCreate()');
},
created() {
	console.log('created()');
},
beforeMount() {
	console.log('beforeMount()');
},
mounted() {
	console.log('mounted()');
},
beforeUpdate() {
	console.log('beforeUpdate()');
},
updated() {
	console.log('updated()');
},
beforeDestroy() {
	console.log('beforeDestroy()');
}

导航跳转

实操代码:

代码语言:vue
复制
<template>
	<view>
		<text>导航跳转</text>
		<navigator url="/pages/detail/detail?name=撩课&site=itlike.com" open-type="navigate">
			<button type="primary">跳转我的详情页</button>
		</navigator>
		<navigator url="/pages/index/index" open-type="switchTab" style="margin-top: 30rpx;">
			<button type="warn">跳转首页</button>
		</navigator>
		<navigator url="/pages/detail/detail" open-type="redirect" style="margin-top: 30rpx;">
			<button type="primary">跳转我的详情页</button>
		</navigator>

		<button type="default" @click="goMineDetail" style="margin-top: 30rpx;">跳转我的详情页</button>
		<button type="default" @click="goHome" style="margin-top: 30rpx;">跳转首页</button>
		<button type="default" @click="redirectDetail" style="margin-top: 30rpx;">跳转我的详情页</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {

			}
		},
		methods: {
			goMineDetail() {
				// 保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面
				uni.navigateTo({
					url: "/pages/detail/detail"
				})
			},
			goHome() {
				// 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
				uni.switchTab({
					url: "/pages/index/index"
				})
			},
			redirectDetail() {
				// 关闭当前页面,跳转到应用内的某个页面。
				uni.redirectTo({
					url: "/pages/detail/detail"
				})
			}
		}
	}
</script>

<style>

</style>

想要完美的看如上的示例,需要自行创建一个详情页,就是 detail.vue,然后在 pages.json 当中配置一下详情页的路由。

上拉和下拉刷新

  • 有全局的配置上拉和下拉的刷新特效我们需要关闭,如果你有全部页面都需要提供上拉下拉刷新的需求可以进行打开即可,这里博主只是进行演示所以就开发一个页面的即可

关闭全局的上拉下拉刷新:

  • 开启某一个页面的上拉下拉刷新
代码语言:json
复制
// 开启上拉下拉刷新功能
"enablePullDownRefresh": true,

course.vue:

代码语言:vue
复制
<template>
	<view>
		<view class="item" v-for="(item, index) in listData">
			<text>{{item.title}}</text>
		</view>
		<button class="load-btn" type="primary" @click="loadNewData">加载新数据</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				listData: [],
				loaded: 0,
				oldLoaded: 0
			}
		},
		onLoad() {
			this.listData = Array.from(new Array(50)).map((value, index) => ({
				title: '初始化数据列表' + index
			}));
			console.log(this.listData);
		},
		onPullDownRefresh() {
			console.log('触发了')
			this.loadNewData();
		},
		onReachBottom() {
			console.log('页面滚动到底部');
			this.loadOldData();
		},
		methods: {
			// 下拉刷新
			loadNewData() {
				uni.showLoading({
					title: '正在加载新数据...'
				});
				setTimeout(() => {
					this.listData = Array.from(new Array(5)).map((value, index) => ({
						title: '我是拉下来的数据' + (this.loaded + index)
					})).concat(this.listData);
					this.loaded += 5;
					// 停止当前页面下拉刷新
					uni.stopPullDownRefresh();
					uni.hideLoading();
				}, 2000);
			},
			// 上拉加载
			loadOldData() {
				uni.showLoading({
					title: '正在加载旧数据...'
				});
				setTimeout(() => {
					let oldDataArr = Array.from(new Array(5)).map((value, index) => ({
						title: '我是上拉的数据' + (this.oldLoaded + index)
					}));
					this.listData = this.listData.concat(oldDataArr);
					this.oldLoaded += 5;
					// 停止当前页面下拉刷新
					uni.stopPullDownRefresh();
					uni.hideLoading();
				}, 2000);
			}
		}
	}
</script>

<style lang="scss">
	.item {
		width: 750rpx;
		height: 88rpx;
		line-height: 88rpx;
		border-bottom: 1px solid #F0F0F0;
		padding-left: 20rpx;
	}

	.load-btn {
		position: fixed;
		right: 0;
		top: 500rpx;
	}
</style>

onReachBottom使用注意 可在pages.json里定义具体页面底部的触发距离 onReachBottomDistance,比如设为50,那么滚动页面到距离底部50px时,就会触发onReachBottom事件。

网络请求和数据缓存

网络请求
代码语言:vue
复制
<template>
	<view>
		<button @click="getRequest">发送Get请求</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {

			}
		},
		methods: {
			getRequest() {
				uni.request({
					// 仅为示例,并非真实接口地址。
					url: 'http://localhost:3000/api/v1/user',
					success: (res) => {
						console.log(res.data);
						this.text = 'request success';
					}
				});
			}
		}
	}
</script>

<style>
</style>
本地缓存
代码语言:vue
复制
<template>
	<view>
		<text>本地缓存</text>
		<view>
			<button type="primary" style="margin-top: 20rpx;" @click="setData">存数据</button>
			<button type="warn" style="margin-top: 20rpx;" @click="getData">取数据</button>
			<button type="primary" style="margin-top: 20rpx;" @click="delData">删除数据</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {

			}
		},
		methods: {
			// 1. 存数据
			setData() {
				uni.setStorage({
					key: 'BNTang',
					data: {
						name: '小灰灰',
						address: '上海',
						site: 'it6666.top'
					},
					success: function() {
						console.log('存储成功了');
					},
					fail: function() {
						console.log('存储失败了');
					},
				})
			},
			
			// 2. 取数据
			getData() {
				uni.getStorage({
					key: 'BNTang',
					success: function(res) {
						console.log(res.data);
					}
				});
			},
			
			// 3. 移除数据
			delData() {
				uni.removeStorage({
					key: 'BNTang',
					success: function(res) {
						console.log('删除成功!');
					}
				});
			}
		}
	}
</script>

<style>
</style>

条件编译

代码语言:vue
复制
<template>
	<view>
		<text>条件编译</text>
		<!-- #ifdef H5  -->
		<view class="web-box">
			只在H5平台显示
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-WEIXIN -->
		<view class="weixin-box">
			只在微信小程序平台显示
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-WEIXIN || APP-PLUS -->
		<view class="weixin-app-box">
			只在微信小程序平台和手机上显示
		</view>
		<!-- #endif -->

		<view class="box"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {

			}
		},
		onLoad() {
			// #ifdef H5
			console.log('只在H5平台显示');
			// #endif

			// #ifdef MP
			console.log('只在小程序平台显示');
			// #endif

			// #ifdef APP-PLUS
			console.log('只在手机上显示');
			// #endif
		},

		methods: {

		}
	}
</script>

<style lang="scss">
	/* #ifdef H5 */
	.weixin-box {
		width: 300rpx;
		height: 300rpx;
		background-color: green;
		margin-top: 30rpx;
	}

	/* #endif */

	.box {
		width: 300rpx;
		height: 300rpx;

		// #ifdef H5
		background-color: red;
		// #endif

		// #ifdef MP
		background-color: purple;
		// #endif

		// #ifdef APP-PLUS
		background-color: pink;
		// #endif

		border-radius: 50%;
		margin-top: 40rpx;
	}
</style>

测试条件编译,方式就是查看一下在某个平台才会执行的条件的内容如果有了而其它的内容只会在其它的平台执行,在当前平台没有执行即可说明成功。

地图绘制

  • 相关示例
代码语言:vue
复制
<template>
	<view>
		<map id="map" style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :scale="5"/>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				latitude: 31.231706,
				longitude: 121.472644,
			}
		},
		methods: {

		}
	}
</script>

<style lang="scss">
</style>

注意点:如果报了 [system] Map key not configured.

移动商城环境配置

微信小程序配置

  • 步骤,进入电商项目,点击工具栏的运行 -> 运行到小程序模拟器 -> 微信开发者工具,即可在微信开发者工具里面体验电商项目

注意事项: 1) 如果是第一次使用,需要先配置小程序ide的相关路径,才能运行成功, 安装小程序IDE, 2) 需在输入框输入微信开发者工具的安装路径

2.支付宝小程序配置,同上

3.Android模拟器配置,1) 安装夜神模拟器,2) 配置adb路径,D:\Program Files\Nox\bin,2) 配置模拟器端口,62001

4.iOS真机配置,1) 安装iTunes,2) 调试注意事项

5.真机调试注意事项:https://ask.dcloud.net.cn/article/97

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Uni-App 简介
    • 框架介绍
      • 框架生态
        • 源码地址
          • 框架分析
          • Uni-App 环境搭建
            • 安装 hbuilderX
              • 安装夜神模拟器
                • 配置环境
                  • 插件市场插件安装
                  • Uni-App 快速入门
                    • 框架简介
                      • 核心技术点
                        • 环境配置
                        • 多端运行
                        • 目录结构分解
                        • 底部 Tab 配置
                        • easycom 和 condition
                        • 常用组件
                        • 响应式单位
                        • 样式和插件使用
                        • 轮播组件
                        • 生命周期
                        • 导航跳转
                        • 上拉和下拉刷新
                        • 网络请求和数据缓存
                        • 条件编译
                        • 地图绘制
                    • 移动商城环境配置
                      • 微信小程序配置
                      相关产品与服务
                      云开发 CloudBase
                      云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档