uniapp常用功能代码

获取视频第一帧

:src="item.videourl+ '?x-oss-process=video/snapshot,t_0,f_jpg'"

隐藏状态栏和虚拟按键

plus.navigator.setFullscreen(true) //隐藏状态栏
plus.navigator.hideSystemNavigation() //隐藏虚拟按键

常用class

样式绑定
:class="[{'box1': key==currentIndex}, 'box2']"

循环绑定
<text>{{item}} {{index==0?num1Count:index==1?num2Count:''}} </text>

Nvue滚动绑定

1.<scroller style="height: 300rpx;background-color: pink;">
			<view v-for="(item,index) in 100" :ref="'content'+index">111</view>
		</scroller>
2.const dom = weex.requireModule('dom');
3.gotoBottom(){
					var doc="content"+99;//最后一项
					dom.scrollToElement(this.$refs[doc][0], {
						offset:0,
						animated:false
					});
			}
4.mounted() {			
			 this.gotoBottom();
		}

前端-常用时间

 var date = new Date(),
				year = date.getFullYear(),
				month = date.getMonth() + 1,
				day = date.getDate(),
				hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
				minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
				second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
			month >= 1 && month <= 9 ? (month = '0' + month) : '';
			day >= 0 && day <= 9 ? (day = '0' + day) : '';
			var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
			console.log(JSON.stringify(timer));

安装time.js

1.npm install time-operation --save
2.import $time from "@/js/time.js"
3.console.log($time.formatTime(1616623902000));

Nvue页面添加阿里图标字体文件

1.app.vue底下style里加

@font-face {
	font-family: 'iconfont';
	src: url('https://at.alicdn.com/t/font_2449187_n9b19w5d3zi.ttf') format('truetype');
}
.myFont {
	font-family: iconfont;
}

onLaunch底下加

const domModule = weex.requireModule('dom');
		domModule.addRule('fontFace', {
			fontFamily: 'iconfont',
			src: "url('https://at.alicdn.com/t/font_2449187_n9b19w5d3zi.ttf')"
		});

2.指定页面加

<text class="myFont" style="font-size: 30px;">&#xe79d;</text>

ios隐藏安全距离-安卓虚拟按键背景色

1.在manifest.json底下app-plus下面加

"safearea": {
			"bottom": {
				"offset": "none"
			}
		}

2.在指定页面加

	var Color = plus.android.importClass("android.graphics.Color");    
	    plus.android.importClass("android.view.Window");    
	    var mainActivity = plus.android.runtimeMainActivity();    
	    var window_android = mainActivity.getWindow();    
	    window_android.setNavigationBarColor(Color.GREEN);

swiper动画绑定

:style="{width:bar+'px',transform:offset}"
return {
offset:"translateX("+uni.getSystemInfoSync().windowWidth/4+")"
}

模拟器上访问本机资源

可以用10.0.2.2代替127.0.0.1和localhost;

复杂运算-计算属性

data{},后加

computed: {
		    user_number:  ()=> {
		      return uni.getStorageSync('number')
		    }
	  }
<view  v-if="item.userid==user_number">

三元运算符

:class="[isState==true?'text':'text1']"

//text和text1为样式

读取本地json数据

1.新建sin.json文件

{
	"sin":123
}
var  sin = require( '../../json/sin.json' );
console.log(sin.sin);

弹出框覆盖导航栏

1.新建sub文件,底下放test.nvue文件

<template>
	<view style="align-items: center;justify-content: center;background-color: red;">
		<image src="../../../static/logo.png" mode="aspectFill" style="width: 100rpx;height: 100rpx;"></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},
		methods: {
			
		}
	}
</script>

<style>

</style>

2.配置pages.json

"pages": [{
		"path": "pages/index/index",
		"style": {
			"navigationBarTitleText": "uni-app",
			"app-plus":{
				"subNVues":[{
					"id":"sin",
					"path":"pages/index/sub/test",
					"type":"popup",
					"style":{
						"margin":"auto",
						"width":"85%",
						"height":"300rpx",
						"border-radius":"10rpx"
					}
				}]
			}
		}
	}]

3.主页面直接调用
uni.getSubNVueById(“sin”).show(“none”,250)

自定义uni组件

1.新建com目录,目录下新建sin.vue文件

<template>
	<view style="background-color: red;width: 200rpx;height: 200rpx;">
		{{title}}
	</view>
</template>

<script>
	export default {
		props:{
			title:""
		},
		data() {
			return {
				
			}
		},
		methods: {
			
		}
	}
</script>

<style>

</style>

2.页面上直接应用就ok

<template>
	<view>
		<sin title="123"></sin>
	</view>
</template>

<script>
	import sin from '@/com/sin.vue'
	export default {
		components: {
			sin
		},

		data() {
			return {

			}
		},
		onLoad() {

		},
		methods: {

		}
	}
</script>

<style>
	
</style>

修改input光标颜色

style{
caret-color: red;
}

修改状态栏图标颜色

	"navigationBarTextStyle": "white",//修改状态栏图标颜色只支持white/black

提示微信开发者工具manifest.json源码视图加上

"app-plus" : {
"compilerVersion" : 3
}

动画过渡(基于uni-ui)

<template>
	<view>
		<view>
			<button type="primary" @click="open">fade</button>
			<uni-transition :mode-class="['fade','slide-top']" :show="show" @change="change"  :styles="obj"/>
		</view>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show: false,
				obj:{
					width:"100px",
					height:"100px",
					backgroundColor:"red"
				}
			}
		},
		methods: {
			open() {
				this.show = !this.show
			},
			change() {
				console.log('触发动画')
			}
		}
	}
</script>

<style>

</style>

压缩并上传图片(同步)

async header1() { //上传
				var headerPath = await this.choose(); //选择图片临时路径
				console.log(headerPath);
				var file_path = await this.compress(headerPath); //压缩后的图片路径
				console.log("压缩后的图片路径" + file_path);
				var uploadPath = await this.upload(file_path);
				console.log("上传完毕地址"+uploadPath);
				this.header_img=file_path;
			},
			choose() { //选择图片
				return new Promise((res) => {
					uni.chooseImage({
						count: 1,
						success: (chooseImageRes) => {
							const tempFilePaths = chooseImageRes.tempFilePaths;
							res(tempFilePaths[0])
						}
					})
				})
			},
			compress(img_path) { //压缩图片
				return new Promise((resolve) => {

					plus.io.resolveLocalFileSystemURL(img_path, (img_obj) => {
						img_obj.file((file) => {
							console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
							if (file.size > 50480) { //文件大于50k
								plus.zip.compressImage({
										src: img_path,
										dst: "_doc/header.jpg",
										quality: 20,
										overwrite: true //有dst必填否则失败
									},
									(suc) => {
										resolve(suc.target);
										console.log('压缩后图片信息:' + suc.target); // 压缩后图片地址
									}, (err) => {
										console.log('err');
									});
							} else {
								// resolve(imgPath);
								resolve(img_path);
							}
						})
					});

				})
			},
			upload(file_path) {
				return new Promise((resolve) => {
					uni.uploadFile({
						url: href + 'file/upload',
						filePath: file_path,
						name: 'file',
						formData: {
							path: 'user/' + uni.getStorageSync("number"),
							number: uni.getStorageSync("number")
						},
						success: (uploadFileRes) => {
							uni.setStorageSync("header", uploadFileRes.data);
							resolve(uploadFileRes.data)
						}
					});
				})

			},

挂载全局请求

main.js

import { sin } from 'js/api.js';
Vue.prototype.$sin=sin;;

api.js

const myUrl = "http://192.168.101.85:8080/";
export const sin = ((options) => {
	return new Promise((resove, reject) => {
		uni.request({
			url: myUrl + options.url,
			data: options.data,
			method: options.method || "GET",
			success: (res) => {
				resove(res)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
})

页面

async method(){
				const res=await this.$sin({
					url:"tongzhi"
				});
				console.log(res)
			}

nvue刷新+样式

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

		<list style="background-color: #007AFF;">
			<refresh @refresh="onrefresh" :display="refreshing ? 'show' : 'hide'" @pullingdown='onpullingdown' style=" border-width: 0px;border-style: solid;border-color: red;">
				<text style="text-align: center;font-size: 30rpx;" space="emsp">{{refreshText}}</text>
				<loading-indicator></loading-indicator>
			</refresh>
			<cell v-for="i in iis">
				<text>{{i}}</text>
			</cell>
		</list>


	</view>
</template>

<script>
	import obj from '@/js/link.js'
	var href = obj.obj.link();
	export default {
		data() {
			return {
				iis: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
				refreshing: false,
				refreshText: '↓ 下拉刷新'
			}
		},
		methods: {
			onrefresh() {
				if (this.refreshing) return;//过快拦截
				this.refreshing = true;
				setTimeout(() => { //松开还原
					this.refreshing = false;
					this.refreshText = '↓ 下拉刷新'
				}, 1000)
			},
			onpullingdown(e) {
				console.log(e.pullingDistance);
				if(e.pullingDistance>=150){
					this.refreshing = false;
					this.refreshText = '↑ 松开释放'
				}
			
			}
		}
	}
</script>

<style>
	.box {
		height: 100rpx;

		background-image: linear-gradient(to bottom right, #AD18F9, #05DFC7);
	}
</style>


获取设备高度(app)

1.绑定指定view
:style="obj"
2. data绑定
obj: {
		height: ""
	}
3.获取设备高度
const res = uni.getSystemInfoSync();
this.obj.height = res.windowHeight + "px";

下拉刷新

1.普通刷新

打开"enablePullDownRefresh": true
"app-plus": {
					"pullToRefresh": {
						"color": "#FF0000"
					}
} 
放在方法下
onPullDownRefresh() {// 监听下拉刷新动作的执行方法,每次手动下拉刷新都会执行一次
				
				setTimeout(function() {
					uni.stopPullDownRefresh(); //停止下拉刷新动画
				}, 100);
}

2.自定义刷新

"pullToRefresh": {
						"support": true,
						"color": "#FF0000",
						"style": "snow-flake",
						"contentdown": {
							"caption": "下拉可刷新"
						},
						"contentover": {
							"caption": "释放可刷新"
						},
						"contentrefresh": {
							"caption": "正在刷新"
						}
					},

沉浸式导航栏

{
			"path": "pages/dongtai/dongtai",
			"style": {
				"navigationBarTitleText": "我的动态",
				"navigationBarTextStyle": "white",
				"navigationBarBackgroundColor": "#ff0000",
				"enablePullDownRefresh": false,
				"transparentTitle":"auto" //关键句
				// "navigationStyle":"custom"
			}

}

嵌套循环v-for

<view style="display: flex;flex-direction: row;margin: 20rpx;border-bottom: 1px solid #EEEEEE;" v-for="item in arrs">
			<view>
				<image :src="item.header" mode="aspectFit" style="height: 120rpx;width: 120rpx;border-radius: 60rpx;"></image>
			</view>
			<view style="display: flex;flex-direction: column;margin-left: 50rpx;">
				<view>
					<text style="font-size: 30rpx;font-weight: bold;">{{item.content}}</text>
				</view>
				<view>
					<image :src="i" mode="aspectFit" style="height: 150rpx;width: 150rpx;margin: 10rpx;" v-for="i in item.imgs"></image>
				</view>
			</view>
</view>

使用安装uView(界面必须view不能使用div否则渲染不出)

cnpm i uview-ui

// main.js
import uView from "uview-ui";
Vue.use(uView);

/* uni.scss */
@import 'uview-ui/theme.scss';


在App.vue中首行的位置引入,注意给style标签加入lang="scss"属性
<style lang="scss">
	/* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
	@import "uview-ui/index.scss";
</style>


// pages.json
{
	"easycom": {
		"^u-(.*)": "@/uview-ui/components/u-$1/u-$1.vue"
	},
	
	// 此为本身已有的内容
	"pages": [
		// ......
	]
}


修改导航栏字体

onNavigationBarButtonTap(e) {
			if (e.index == 0) { //编辑
				/* uni.setNavigationBarTitle({
				title:"cehi" //这是修改后的导航栏文字
				}) */

				const currentWebview = this.$mp.page.$getAppWebview();
				currentWebview.setTitleNViewButtonStyle(e.index, {
					text: "完成"
				});
				var  txt= currentWebview.getStyle().titleNView.buttons[0].text;
				if(txt=="完成"){
					currentWebview.setTitleNViewButtonStyle(e.index, {
						text: "编辑"
					});
				}else{
					currentWebview.setTitleNViewButtonStyle(e.index, {
						text: "完成"
					});
				}

			} else {

			}
		}

pages.json常用

"app-plus": {
					"titleNView": {
						"splitLine": {
							"color": "#f2f2f2"
						},
						"buttons": [{
								"text": "按钮2",
								"fontSrc": "/static/uni.ttf",
								"fontSize": "22px",
								"float": "left",
								"color": "#FF0000"
							},
							{
								"text": "按钮1",
								"width": "150rpx",
								"fontSrc": "/static/uni.ttf",
								"fontSize": "30rpx",
								"float": "right"
							}
						]
					},
					"pullToRefresh": {
						"color": "#FF0000"
					}
				}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值