Home > Web Front-end > uni-app > uni-app introductory tutorial to master the basic use of components

uni-app introductory tutorial to master the basic use of components

coldplay.xixi
Release: 2021-01-11 09:40:57
forward
3902 people have browsed it

uni-app introductory tutorial to master the basic use of components

Recommended (free): uni-app development tutorial

Article Contents

  • Preface
  • 1. Basic components
    • 1.scroll-view
    • 2.swiper
    • 3.text
    • 4.rich-text
    • 5.process
  • 2. Form component
    • 1.button
    • 2.checkbox
    • 3.input
    • 4.label
    • 5.picker
    • 6.radio
    • 7.slider
    • 8.switch
    • 9.textarea
    • 10.form
  • 3. Navigation component and page parameter passing
    • 1.navigator
    • 2.Parameter passing
  • 4. Media component
    • 1.audio
    • 2.image
    • 3.video
  • Summary

Preface

This article mainly introduces the components in uni-app, including four major categories: basic components (scroll-view, swiper, text, etc. ), form components (button, checkbox, input, etc.), navigation components navigator and page parameters, media components (audio, image, video, etc.), details the common properties and methods of these components, and provides usage examples and demonstrations.

1. Basic components

Components are the basic components of the view layer. A component usually includes a start tag and an end tag. Attributes are used to Modify this component so that the content is within two tags.
All component and attribute names are lowercase, and words are connected with hyphens -. The root node is <template>, and there can only be one root component under it.

The framework provides developers with a series of basic components, and developers can quickly develop by combining these basic components.
Common basic components are as follows:

##progressProgress bar
Component name Description
view View container, similar to p
scroll-view Scrollable view container
swiper Slider view container
icon icon
text Text
rich-text Rich text
view is the most basic view container, similar to p in traditional HTML, used to wrap various element contents.

1.scroll-view

Scrollable view area, used for area scrolling.

Please note that in pages rendered by webview, the performance of area scrolling is not as good as page scrolling.

Common attributes and meanings are as follows:

##Attribute namescroll-xscroll-yupper-threshold##lower-thresholdNumber50How far away from the bottom/right (unit px) is to trigger the scrolltolower eventscroll-topNumberNoneSet the vertical scroll bar positionscroll-leftNumberNoneSet the horizontal scroll bar positionscroll-into-viewStringNoneThe value should be a certain sub-element id (the id cannot start with a number). Set which direction can be scrolled, then scroll to the element in which directionscroll-with-animationBooleanfalseUse animated transitions when setting the scroll bar position enable-flexbooleanfalseEnable flexbox layout. After it is turned on, the current node that declares display: flex will become a flex container and act on its child nodes. Common events and meanings are as follows:
Type Default value Description
Boolean false Allow horizontal scrolling
Boolean false Allow vertical scrolling
Number 50 How far away from the top/left (unit px) is to trigger the scrolltoupper event

EventMeaning@scrolltoupperScroll to the top/left, the scrolltoupper event will be triggered@scrolltolowerScroll to the bottom/right, the scrolltolower event will be triggered@scrollTriggered when scrolling, event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}@refresherpullingThe custom drop-down refresh control is pulled down@refresherrefreshsince Define pull-down refresh to be triggered@refresherrestoreCustomize pull-down refresh to be reset@refresherabortCustomized pull-down refresh was aborted

hello uniapp project, index.vue is as follows:

<template>
	<view>
		<scroll-view class="scv" scroll-x="true">
			<view>1</view>
			<view>2</view>
			<view>3</view>
			<view>4</view>
			<view>5</view>
			<view>6</view>
		</scroll-view>
	</view></template><script>
	var _self;
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			_self = this
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
		}
	}</script><style>
	scroll-view {
		display: flex;
	}
	.scv {
		width: 90%;
		margin: 0 auto;
		background: #F0AD4E;
		flex-wrap: nowrap;
		white-space: nowrap;
	}
	.scv view {
		width: 50%;
		height: 100px;
		background: #007AFF;
		display: inline-block;
	}</style>
Copy after login

Display:
uniapp component basic scrollview

Obviously, horizontal scrolling is possible at this time.

2.swiper

Slider view container, generally used for sliding left and right or up and down, such as banner carousel.

Note:
There is a difference between sliding switching and scrolling. Sliding switching is a screen-by-screen switching. Each swiper-item under the swiper is a sliding switching area and cannot stay at 2 between two sliding areas, and scrolling is allowed to stay between two scrolling areas.

Common attributes and meanings are as follows:

##vertical BooleanfalseWhether the sliding direction is verticalprevious-marginString0pxFront margin, can be used to expose a small part of the previous item, accepts px and rpx valuesnext-margin String0pxBack margin, can be used to expose a small part of the following item, accepts px and rpx values
Attribute name Type Default value Description
indicator-dots Boolean false Whether to display panel indicator dots
indicator-color Color rgba(0, 0, 0, .3) Indicator color
indicator-active-color Color #000000 The color of the currently selected indicator point
active-class String None swiper-item class when visible
changing-class String None acceleration is set to {{true}} and is in the sliding process. The class when several screens in the middle are visible
autoplay Boolean false Whether to switch automatically
current Number 0 The index of the current slider
interval Number 5000 Automatic switching time interval
duration Number 500 Sliding animation duration
circular Boolean false Whether to use connection sliding, that is, play to the end and then return to the beginning
Common events As follows:

EventMeaning##@change## The change event will be triggered when #current changes, event.detail = {current: current, source: source}@transitionWhen the position of swiper-item changes The transition event will be triggered, event.detail = {dx: dx, dy: dy}, Alipay applet does not currently support dx, dy App, H5, WeChat applet, Alipay applet, ByteDance applet, QQ applet@animationfinishThe animationfinish event will be triggered when the animation ends, event.detail = {current: current, source: source}For more information, please refer to https://uniapp.dcloud.io/component/swiper.
index.vue is as follows:

<template>
	<view>
		<swiper :indicator-dots="true" :autoplay="true" :interval="2000" :duration="1000" previous-margin="10px" next-margin="10px">
			<swiper-item>
				<view class="swiper-item uni-bg-red">A</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item uni-bg-green">B</view>
			</swiper-item>
			<swiper-item>
				<view class="swiper-item uni-bg-blue">C</view>
			</swiper-item>
		</swiper>
	</view></template><script>
	var _self;
	export default {
		data() {
			return {}
		},
		onLoad() {
			_self = this
		},
		onShow() {},
		onHide() {},
		methods: {}
	}</script><style>
	swiper-item {
		background: #4CD964;
		height: 200px;
		width: 90%;
	}</style>
Copy after login
Display:


As you can see, the effect of dynamic playback of carousel images is achieved. uniapp component basic swiper

3.text

Text component is used to wrap text content and provide text that can be selected and copied

, while the text of other components None can be selected or copied.

Common attributes are as follows:

Attribute nameTypeDefault valueDescriptionselectableBooleanfalseWhether the text is selectablespaceStringNoneDisplay consecutive spacesdecodeBooleanfalseWhether to decodeThe optional values ​​and meanings of the space attribute are as follows:

ValueMeaning##enspChinese character space half sizeChinese character space sizeSet the space size according to the font4.rich-text
emsp
nbsp

Rich text. Common attributes are as follows:

Attribute nameTypenodesArray / StringstringBoolean
Default value Description
[] Node list/HTML String space
None Display consecutive spaces selectable
false Whether rich text can be selected by long pressing and can be used for copying, pasting and other scenarios

index.vue如下:

<template>
	<view>
		<rich-text :nodes="nodes" @tap="tap"></rich-text>
	</view></template><script>
	var _self;
	export default {
		data() {
			return {
				nodes: [{
					name: 'p',
					attrs: {
						class: 'p-class',
						style: 'line-height: 60px; color: red; text-align:center;'
					},
					children: [{
						type: 'text',
						text: 'Hello uni-app!'
					}]
				}],
				strings: '<p style="text-align:center;"><img src="https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/uni@2x.png"/></p>'
			}
		},
		onLoad() {
			_self = this
		},
		onShow() {},
		onHide() {},
		methods: {}
	}</script><style></style>
Copy after login

显示:
uniapp component basic richtext

显然,渲染出了富文本。

5.process

进度条。

常见属性如下:

属性名 类型 默认值 说明
percent Float 百分比0~100
show-info Boolean false 在进度条右侧显示百分比
stroke-width Number 6 进度条线的宽度,单位px
activeColor Color #09BB07(百度为#E6E6E6) 已选择的进度条的颜色
backgroundColor Color #EBEBEB 未选择的进度条的颜色
active Boolean false 进度条从左往右的动画

index.vue如下:

<template>
	<view>
		<view class="progress-box">
			<progress percent="20" show-info stroke-width="3" />
		</view>
		<view class="progress-box">
			<progress percent="40" active stroke-width="3" />
		</view>
		<view class="progress-box">
			<progress percent="60" active stroke-width="3" backgroundColor="#999" />
		</view>
		<view class="progress-box">
			<progress percent="80" activeColor="red" active stroke-width="8" />
		</view>
	</view></template><script>
	var _self;
	export default {
		data() {
			return {}
		},
		onLoad() {
			_self = this
		},
		onShow() {},
		onHide() {},
		methods: {}
	}</script><style></style>
Copy after login

显示:
uniapp component basic process

可以看到,显示出了进度的动态变化。

二、表单组件

表单组件很常用,主要用于数据的收集和提交

1.button

按钮。

常见的属性和含义如下:

属性名 类型 默认值 说明
size String default 按钮的大小
type String default 按钮的样式类型
plain Boolean false 按钮是否镂空,背景色透明
disabled Boolean false 是否禁用
loading Boolean false 名称前是否带 loading 图标
form-type String 用于 <form> 组件,点击分别会触发 <form> 组件的 submit/reset 事件
open-type String 开放能力

index.vue如下:

<template>
	<view>
		<button type="default" size="defaultSize" :loading="loading" :plain="plain" :disabled="disabled" @tap="defaultHandler" hover-class="other-button-hover">default</button>
		<button type="primary" size="primarySize" :loading="loading" :plain="plain" :disabled="disabled" @tap="primaryHandler">primary</button>
		<button type="warn" size="warnSize" :loading="loading" :plain="plain" :disabled="disabled" @tap="warnHandler">warn</button>
		<button @tap="setDisabled">点击设置以上按钮disabled属性</button>
		<button @tap="setPlain">点击设置以上按钮plain属性</button>
		<button @tap="setLoading">点击设置以上按钮loading属性</button>
	</view></template><script>
	var types = ['default', 'primary', 'warn']
	export default {
		data() {
			return {
				defaultSize: 'default',
				primarySize: 'default',
				warnSize: 'default',
				disabled: false,
				plain: false,
				loading: false
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onUnload() {
		},
		methods: {
			setDisabled: function(e){
				this.disabled = !this.disabled			},
			setPlain: function(e){
				this.plain = !this.plain			},
			setLoading: function(e){
				this.loading = !this.loading			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form button

可以看到,在点击button时,触发了相应的操作。

2.checkbox

checkbox-group是多项选择器,内部由多个 checkbox 组成。

属性如下:

属性名 类型 说明
@change EventHandle <checkbox-group>中选中项发生改变是触发 change 事件,detail = {value:[选中的checkbox的value的数组]}

checkbox是多选项目,即复选框。

常见属性如下:

属性名 类型 默认值 说明
value String <checkbox> 标识,选中时触发 <checkbox-group> 的 change 事件,并携带 <checkbox> 的 value
disabled Boolean false 是否禁用
checked Boolean false 当前是否选中,可用来设置默认选中
color Color checkbox的颜色,同css的color

index.vue如下:

<template>
	<view class="content">
		<checkbox-group name="" @change="checkboxChange">
			<label class="checkbox" v-for="item in items" :key="item">
				<checkbox :value="item" />{{item}}			</label>
		</checkbox-group>
	</view></template><script>
	var _self;
	export default {
		data() {
			return {
				items: ['Reading', 'Running']
			}
		},
		onLoad() {
			_self = this;
			setTimeout(function(){
				_self.age = 20
			}, 3000);
		},
		onShow() {
			console.log('index onshow')
		},
		onHide() {
			console.log('index onhide')
		},
		methods: {
			checkboxChange: function(e) {
				console.log(e)
			}
		}
	}</script><style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}</style>
Copy after login

显示:
uniapp component form checkbox

可以看到,已经渲染出页面元素,同时支持点选。

3.input

输入框。

常见的属性如下:

属性名 类型 默认值 说明
value String 输入框的初始内容
type String text input 的类型
password Boolean false 是否是密码类型
placeholder String 输入框为空时占位符
placeholder-style String 指定 placeholder 的样式
placeholder-class String “input-placeholder” 指定 placeholder 的样式类,注意页面或组件的style中写了scoped时,需要在类名前写/deep/
disabled Boolean false 是否禁用
maxlength Number 140 最大输入长度,设置为 -1 的时候不限制最大长度
confirm-type String done 设置键盘右下角按钮的文字,仅在 type=“text” 时生效。

常见的事件如下:

事件 含义
@input 当键盘输入时,触发input事件,event.detail = {value}
@focus 输入框聚焦时触发,event.detail = { value, height },height 为键盘高度
@blur 输入框失去焦点时触发,event.detail = {value: value}
@confirm 点击完成按钮时触发,event.detail = {value: value}
@keyboardheightchange 键盘高度发生变化的时候触发此事件,event.detail = {height: height, duration: duration}

4.label

用来改进表单组件的可用性,使用for属性找到对应的id,或者将控件放在该标签下,当点击时,就会触发对应的控件。
for优先级高于内部控件,内部有多个控件的时候默认触发第一个控件。
目前可以绑定的控件有<button><checkbox><radio><switch>

属性如下:

属性名 类型 说明
for String 绑定控件的 id

5.picker

从底部弹起的滚动选择器。
支持五种选择器,通过mode来区分,分别是普通选择器、多列选择器、时间选择器、日期选择器和省市区选择器,默认是普通选择器。

(1)普通选择器,参数为mode = selector,常见属性和事件如下:

属性名 类型 说明
range Array / Array mode为 selector 或 multiSelector 时,range 有效
@change EventHandle value 改变时触发 change 事件,event.detail = {value: value}

index.vue如下:

<template>
	<view>
		<picker :range="years" @change="yearChange">
			<view>
				{{years[yearIndex]}}			</view>
		</picker>
	</view></template><script>
	export default {
		data() {
			return {
				years: ["请选择年份", 2019, 2020, 2021],
				yearIndex: 0
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onUnload() {
		},
		methods: {
			yearChange: function(e){
				console.log(e)
				this.yearIndex = e.detail.value			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form picker normal

可以看到,在选择值后,显示也会同步变化,被选择的值的下标存储在e.detail.value中。

(2)多列选择器,参数为mode = multiSelector,常见属性和事件如下:

属性名 类型 说明
range 二维 Array / 二维 Array mode为 selector 或 multiSelector 时,range 有@change

index.vue如下:

<template>
	<view>
		<picker mode="multiSelector" :range="years" @change="yearChange">
			<view>
				{{years[0][yearIndex]}}-{{years[1][monthIndex]}}			</view>
		</picker>
	</view></template><script>
	export default {
		data() {
			return {
				years: [
					["请选择年份", 2019, 2020, 2021],
					["请选择月份 ", 3, 4, 5]
				],
				yearIndex: 0,
				monthIndex: 0
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onUnload() {
		},
		methods: {
			yearChange: function(e){
				console.log(e)
				this.yearIndex = e.detail.value[0],
				this.monthIndex = e.detail.value[1]
			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form picker multi

显然,可以进行多级选择,此时e.detail.value是一个数组,可以分别取值;
还可以通过ajax等方式实现先选择一级、再动态显示二级。

(3)时间选择器,参数为mode = time,常见属性和事件如下:

属性名 类型 说明
value String 表示选中的时间,格式为"hh:mm"
start String 表示有效时间范围的开始,字符串格式为"hh:mm" App 不支持
end String 表示有效时间范围的结束,字符串格式为"hh:mm" App 不支持
@change EventHandle value 改变时触发 change 事件,event.detail = {value: value}

index.vue如下:

<template>
	<view>
		<picker mode="time" @change="yearChange">
			<view>
				{{timeText}}			</view>
		</picker>
	</view></template><script>
	export default {
		data() {
			return {
				timeText: "请选择时间"
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onUnload() {
		},
		methods: {
			yearChange: function(e){
				console.log(e);
				this.timeText = e.detail.value			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form picker time

(4)日期选择器,参数为mode = date,常见属性和事件如下:

属性名 类型 说明
value String 表示选中的日期,格式为"YYYY-MM-DD"
start String 表示有效日期范围的开始,字符串格式为"YYYY-MM-DD"
end String 表示有效日期范围的结束,字符串格式为"YYYY-MM-DD"
fields String 有效值 year、month、day,表示选择器的粒度,默认为 day,App 端未配置此项时使用系统 UI
@change EventHandle value 改变时触发 change 事件,event.detail = {value: value}

(5)省市区选择器,参数为mode = region,常见属性和事件如下:

属性名 类型 说明
value Array 表示选中的省市区,默认选中每一列的第一个值
custom-item String 可为每一列的顶部添加一个自定义的项
@change EventHandle value 改变时触发 change 事件,event.detail = {value: value}
@cancel EventHandle 取消选择时触发

index.vue如下:

<template>
	<view>
		<picker mode="region" @change="regionChange">
			<view>
				{{regionText}}			</view>
		</picker>
	</view></template><script>
	export default {
		data() {
			return {
				regionText: "请选择地区"
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onUnload() {
		},
		methods: {
			regionChange: function(e){
				console.log(e);
				this.regionText = e.detail.value			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form picker region

显然,控制台输出了对应省市区的编码和文本。

6.radio

radio-group是单项选择器,内部由多个 <radio> 组成,通过把多个radio包裹在一个radio-group下,实现这些radio的单选。

属性如下:

属性名 类型 说明
@change EventHandle <radio-group> 中的选中项发生变化时触发 change 事件,event.detail = {value: 选中项radio的value}

radio即单选项目,常见属性如下:

属性名 类型 默认值 说明
value String <radio> 标识。当该 <radio> 选中时,<radio-group> 的 change 事件会携带 <radio> 的 value
checked Boolean false 当前是否选中
disabled Boolean false 是否禁用
color Color radio的颜色,同css的color

7.slider

滑动选择器,常见属性和含义如下:

属性名 类型 默认值 说明
min Number 0 最小值
max Number 100 最大值
step Number 1 步长,取值必须大于 0,并且可被(max - min)整除
disabled Boolean false 是否禁用
value Number 0 当前取值
activeColor Color 微信是绿色(#1aad19),头条是红色,其他平台是蓝色 滑块左侧已选择部分的线条颜色
backgroundColor Color #e9e9e9 滑块右侧背景条的颜色
block-size Number 28 滑块的大小,取值范围为 12 - 28
block-color Color #ffffff 滑块的颜色
show-value Boolean false 是否显示当前 value
@change EventHandle 完成一次拖动后触发的事件,event.detail = {value: value}

index.vue如下:

<template>
	<view>
		<slider @change="sliderChange" step="5"></slider>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onUnload() {
		},
		methods: {
			sliderChange: function(e){
				console.log(e);
			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form slider

可以看到,获取到了滑动选择器的值。

8.switch

开关选择器。

常见属性和含义如下:

属性名 类型 默认值 说明
checked Boolean false 是否选中
disabled Boolean false 是否禁用
type String switch 样式,有效值:switch, checkbox
color Color switch 的颜色,同 css 的 color
@change EventHandle checked 改变时触发 change 事件,event.detail={ value:checked}

index.vue如下:

<template>
	<view>
		<switch @change="switchChange"></switch>
	</view></template><script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
		},
		onShow() {
		},
		onUnload() {
		},
		methods: {
			switchChange: function(e){
				console.log(e);
			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form switch

可以看到,在选择器处于打开状态时,value为true,处于关闭状态时,value为false。

9.textarea

多行输入框。

常见属性和事件如下:

属性名 类型 默认值 说明
value String 输入框的内容
placeholder String 输入框为空时占位符
placeholder-style String 指定 placeholder 的样式
placeholder-class String textarea-placeholder 指定 placeholder 的样式类
disabled Boolean false 是否禁用
maxlength Number 140 最大输入长度,设置为 -1 的时候不限制最大长度
focus Boolean false 获取焦点
@focus EventHandle 输入框聚焦时触发,event.detail = { value, height },height 为键盘高度
@blur EventHandle 输入框失去焦点时触发,event.detail = {value, cursor}
@linechange EventHandle 输入框行数变化时调用,event.detail = {height: 0, heightRpx: 0, lineCount: 0}
@input EventHandle 当键盘输入时,触发 input 事件,event.detail = {value, cursor}, @input 处理函数的返回值并不会反映到 textarea 上
@confirm EventHandle 点击完成时, 触发 confirm 事件,event.detail = {value: value}

10.form

表单,将组件内的用户输入的<switch><input><checkbox><slider><radio><picker>中的数据提交。
当点击 <form> 表单中 formType 为 submit 的 <button> 组件时,会将表单组件中的 value 值进行提交,需要在表单组件中加上 name 来作为 key。

常见属性和含义如下:

属性名 类型 说明
report-submit Boolean 是否返回 formId 用于发送模板消息
@submit EventHandle 携带 form 中的数据触发 submit 事件,event.detail = {value : {‘name’: ‘value’} , formId: ‘’},report-submit 为 true 时才会返回 formId
@reset EventHandle 表单重置时会触发 reset 事件

index.vue如下;

<template>
	<view>
		<form @submit="formSubmit" @reset="formReset">
			<view class="section section_gap">
				<view class="section__title">switch</view>
				<switch name="switch" />
			</view>
			<view class="section section_gap">
				<view class="section__title">slider</view>
				<slider name="slider" show-value="" />
			</view>
			<view class="section">
				<view class="section__title">input</view>
				<input name="input" placeholder="please input here" />
			</view>
			<view class="section section_gap">
				<view class="section__title">radio</view>
				<radio-group name="radio-group">
					<label>
						<radio value="radio1" /><text>radio1</text>
					</label>
					<label>
						<radio value="radio2" /><text>radio2</text>
					</label>
				</radio-group>
			</view>
			<view class="section section_gap">
				<view class="section__title">checkbox</view>
				<checkbox-group name="checkbox">
					<label>
						<checkbox value="checkbox1" /><text>checkbox1</text>
					</label>
					<label>
						<checkbox value="checkbox2" /><text>checkbox2</text>
					</label>
				</checkbox-group>
				<input name="input" placeholder="please input here" />
			</view>
			<view class="btn-area">
				<button form-type="submit">Submit</button>
				<button form-type="reset">Reset</button>
			</view>
		</form>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {},
		onShow() {},
		onUnload() {},
		methods: {
			formSubmit: function(e) {
				var formData = e.detail.value;
				console.log(formData);
				if (!formData.switch) {
					console.log('No Pass')
				}
			},
			formReset: function(e) {
				console.log(e)
			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component form form

可以看到,在点击Submit按钮提交之后,会将数据全部提交,还可以对数据进行验证。

三、导航组件和页面传参

1.navigator

导航组件用于页面跳转,类似HTML中的<a>组件,但只能跳转本地页面,即目标页面必须在pages.json中注册。

常见的属性和含义如下:

属性名 类型 默认值 说明
url String 应用内的跳转链接,值为相对路径或绝对路径,如:"…/first/first","/pages/first/first",注意不能加 .vue 后缀
open-type String navigate 跳转方式,与api接口相对应
delta Number 当 open-type 为 ‘navigateBack’ 时有效,表示回退的层数
target String self 在哪个小程序目标上发生跳转,默认当前小程序,值域self/miniProgram

其中, open-type对应的API接口及其含义如下:

接口 含义
uni.navigateTo(OBJECT) 保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面
uni.redirectTo(OBJECT) 关闭当前页面,跳转到应用内的某个页面
uni.reLaunch(OBJECT) 关闭所有页面,打开到应用内的某个页面
uni.switchTab(OBJECT) 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
uni.navigateBack(OBJECT) 关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层

index.vue如下:

<template>
	<view>
		<navigator url="../news" hover-class="navigator-hover">
			<button type="default">跳转到news页面</button>
		</navigator>
		<navigator url="../about/about" open-type="switchTab" hover-class="navigator-hover">
			<button type="default">跳转到about页面</button>
		</navigator>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {},
		onShow() {},
		onUnload() {},
		methods: {
		}
	}</script><style></style>
Copy after login

显示:
uniapp component navigator basic

可以看到,实现了两种方式的跳转。

这是通过DOM进行页面跳转,还可以通过API进行跳转,如下:

<template>
	<view>
		<button type="default" @click="skip">跳转到新闻页面</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {},
		onShow() {
			setTimeout(function(){
				uni.navigateBack({
					delta: 1
				})
			}, 3000)			
		},
		onUnload() {},
		methods: {
			skip: function() {
				uni.navigateTo({
					url: '../news'
				})
			}
		}
	}</script><style></style>
Copy after login

显示:
uniapp component navigator js

可以看到,也实现了页面跳转,并且可以定时跳转回原页面。

2.参数传递

在进行页面跳转时,向其他页面传递参数一般在组件或接口的url参数指定的地址后追加,以?开始,=连接参数名和参数值,&拼接不同的参数。

index.vue传递参数如下:

<template>
	<view>
		<button type="default" @click="skip">跳转到新闻页面</button>
	</view></template><script>
	export default {
		data() {
			return {}
		},
		onLoad() {},
		onShow() {
			setTimeout(function(){
				uni.navigateBack({
					delta: 1
				})
			}, 5000)			
		},
		onUnload() {},
		methods: {
			skip: function() {
				uni.navigateTo({
					url: '../news?size=20&page=1'
				})
			}
		}
	}</script><style></style>
Copy after login

news.vue接收参数如下:

<template>
	<view class="content">新闻页</view></template><script>
	export default {
		onLoad:function(options){
			console.log(options)
		}
	}</script><style></style>
Copy after login

显示:
uniapp component navigator send param

可以看到,参数值保存在options中。

四、媒体组件

1.audio

音频组件。

常见属性和事件如下:

属性名 类型 默认值 说明
id String audio 组件的唯一标识符
src String 要播放音频的资源地址
loop Boolean false 是否循环播放
controls Boolean false 是否显示默认控件
poster String 默认控件上的音频封面的图片资源地址,如果 controls 属性值为 false 则设置 poster 无效
name String 未知音频
author String 未知作者 默认控件上的作者名字,如果 controls 属性值为 false 则设置 author 无效
@error EventHandle 当发生错误时触发 error 事件,detail = {errMsg: MediaError.code}
@play EventHandle 当开始/继续播放时触发play事件
@pause EventHandle 当暂停播放时触发 pause 事件
@timeupdate EventHandle 当播放进度改变时触发 timeupdate 事件,detail = {currentTime, duration}
@ended EventHandle 当播放到末尾时触发 ended 事件

index.vue如下:

<template>
	<view>
		<audio :src="audioSrc" :poster="posterSrc" :name="name" :author="author" controls style="text-align: center;"></audio>
	</view></template><script>
	export default {
		data() {
			return {
				audioSrc: "https://m10.music.126.net/20201221165005/b4e7a310f6e3ffda9f12ab518201087c/yyaac/obj/wonDkMOGw6XDiTHCmMOi/2513074700/92fc/e94b/8333/c8592b8e05995aa1744976275eb09ab0.m4a",
				posterSrc: "https://y.gtimg.cn/music/photo_new/T002R300x300M000002npMQN1wN8nZ_1.jpg?max_age=2592000",
				name: "Blackheart",
				author: "Thomas Bergersen / Two Steps From Hell"
			}
		},
		onLoad() {},
		onShow() {
						
		},
		onUnload() {},
		methods: {
			
		}
	}</script><style>
	audio {
		background: #007AFF;
		width: 100%;
	}</style>
Copy after login

显示:

uniapp component media audio

可以看到,实现了音乐播放功能。

2.image

图片组件。

常见的属性和事件如下:

属性名 类型 默认值 说明
src String 图片资源地址
mode String ‘scaleToFill’ 图片裁剪、缩放的模式
lazy-load Boolean false 图片懒加载。只针对page与scroll-view下的image有效
fade-show Boolean true 图片显示动画效果
webp boolean false 默认不解析 webP 格式,只支持网络资源
show-menu-by-longpress boolean false 开启长按图片显示识别小程序码菜单
@error HandleEvent 当错误发生时,发布到 AppService 的事件名,事件对象event.detail = {errMsg: ‘something wrong’}
@load HandleEvent 当图片载入完毕时,发布到 AppService 的事件名,事件对象event.detail = {height:‘图片高度px’, width:‘图片宽度px’}

index.vue如下:

<template>
	<view>
		<image src="../../static/imgs/saying.png" style="width: 55%;"></image>
		<image src="../../static/imgs/saying.png" style="height: 200rpx;" mode="top right"></image>
		<image src="../../static/imgs/saying.png" style="width: 55%;" mode="widthFix"></image>
	</view></template><script>
	export default {
		data() {
			return {
				
			}
		},
		onLoad() {},
		onShow() {
					
		},
		onUnload() {},
		methods: {
			
		}
	}</script><style>
	</style>
Copy after login

显示:
uniapp component media image
可以看到,mode属性值不同,图片显示的形式也会有所区别。

3.video

视频组件。

常见属性和事件如下:

属性名 类型 默认值 说明
src String 要播放视频的资源地址
autoplay Boolean false 是否自动播放
loop Boolean false 是否循环播放
muted Boolean false 是否静音播放
initial-time Number 指定视频初始播放位置,单位为秒(s)
duration Number 指定视频时长,单位为秒(s)
controls Boolean true 是否显示默认播放控件(播放/暂停按钮、播放进度、时间)
show-progress Boolean true 若不设置,宽度大于240时才会显示
poster String 视频封面的图片网络资源地址,如果 controls 属性值为 false 则设置 poster 无效
@play EventHandle 当开始/继续播放时触发play事件
@pause EventHandle 当暂停播放时触发 pause 事件
@ended EventHandle 当播放到末尾时触发 ended 事件
@timeupdate EventHandle 播放进度变化时触发,event.detail = {currentTime, duration} 。触发频率 250ms 一次
@fullscreenchange EventHandle 当视频进入和退出全屏时触发,event.detail = {fullScreen, direction},direction取为 vertical 或 horizontal
@waiting EventHandle 视频出现缓冲时触发
@error EventHandle 视频播放出错时触发
@progress EventHandle 加载进度变化时触发,只支持一段加载。event.detail = {buffered},百分比
@controlstoggle eventhandle 切换 controls 显示隐藏时触发。event.detail = {show}

index.vue如下:

<template>
	<view>
		<video id="myVideo" src="https://vodkgeyttp9.vod.126.net/cloudmusic/N0qR6445_2249845426_hd.mp4?ts=1608546147&rid=C127086D22ABA8524D81BF20C706B22B&rl=3&rs=WPEhneQzZWbNSeETGHhAruzsoNATDuXC&sign=80864b2eb815f570c9ce0ca4e31a9b72&ext=XHOm0M2rNgl%252BOsuwtVhiXa7BA9%252FkbvJfK84GXv1FFd7SvvDty%252BQ0GH9eXueIlfcwNUnGHRzfhbEYqUYBZ7ygZIdke%252Bg2SpJHDq4lJBw1rnmQ3PMGLXkM3%252BzAlTLvRhAxrxz0O5mQJ%252BELGODgy6G%252Bp7lrZ1TUmeJpqovjqqiZ3g%252Bq8iLxQWFUOajn5NyiEBuv18Eb9Z%252FfrLVHVrjYvXEBAR6M3eYxHG13DGON2%252F0sniI%252FWdCjmuGWL6wk8NtEzV32kPjquU4yMUiMBX%252B3NYu70c9OUnBc4npLNLG2qBCjKxA8qv2Zyn7UjC3n4rvTjyQBnmMrh8ey%252FffGWXHOsrge088Wr7oVoVcCWbHlGaFyTJ9hgVfe%252F6%252BddmLZVuYT0mZ%252Ft4JPaSdoVAoujK54TRcwW9i5T4toFrUWjn1b13qquz3s%252FySUUnvfEF65s7Z1AjCdvoCG6LrShGdY%252Fu2yre8HDZVyHVjeAoYtbvG5VXQDVm1W74z%252BdRSLxp0Bml7L27EsVZlXaSqn32KJlR4fr4%252FvrgW5GrjiflWoOoyOZ1RK0sk%253D" enable-danmu danmu-btn controls></video>
	</view></template><script>
	export default {
		data() {
			return {
				
			}
		},
		onLoad() {},
		onShow() {
					
		},
		onUnload() {},
		methods: {
			
		}
	}</script><style>
	</style>
Copy after login

显示:

uniapp component media video

The above is the detailed content of uni-app introductory tutorial to master the basic use of components. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template