uni-app 学习笔记

1. uni-app 基础

官方文档

1.1 什么是uni-app

  • uni-app是一个使用Vue.js语法来开发所有前端应用的框架(也称之为全端开发框架)
  • 开发者编写一套代码,可发布到iOSAndroidWeb(响应式)、以及各种小程序(微信/支付宝/百度/头条/QQ/快手/钉钉/淘宝)、快应用等多个平台。
  • 技术栈:JavaScriptvue微信小程序uni-app

1.2 uni-app的优点

uni-app在开发者数量、案例、跨端抹平度、扩展灵活性、性能体验、周边生态、学习成本、开发成本等8大关键指标上拥有更强的优势

1.跨平台、平台能力不受限

2.运行体验更好

  • 组件、api与微信小程序一致
  • 兼容weex原生渲染

3.通用技术栈,学习成本更低

  • vue的语法、微信小程序的api
  • 内嵌mpvue

4.开放生态,组件更丰富

  • 支持安装第三方包
  • 支持微信小程序自定义组件及SDK
  • 兼容mpvue组件及项目
  • App段支持和原生混合编码
  • DCloud将发布插件市场

1.3 页面生命周期

函数名作用
onInit监听页面初始化,其参数同 onLoad 参数,为上个页面传递的数据,参数类型为 Object(用于页面传参),触发时机早于 onLoad
onLaunch监听页面加载,其参数为上个页面传递的数据,参数类型为 Object(用于页面传参)
onShow监听页面显示。页面每次出现在屏幕上都触发,包括从下级页面点返回露出当前页面
onReady监听页面初次渲染完成。注意如果渲染速度快,会在页面进入动画完成前触发
onHide监听页面隐藏
onUnload监听页面卸载
onResize监听窗口尺寸变化
onPullDownRefresh监听用户下拉动作,一般用于下拉刷新
onReachBottom页面滚动到底部的事件(不是scroll-view滚到底),常用于下拉下一页数据。
onTabItemTap点击 tab 时触发,参数为Object
onShareAppMessage用户点击右上角分享
onPageScroll监听页面滚动,参数为Object
onShareAppMessage用户点击右上角分享
onNavigationBarButtonTap监听原生标题栏按钮点击事件,参数为Object
onShareAppMessage用户点击右上角分享
onShareTimeline监听用户点击右上角转发到朋友圈
onAddToFavorites监听用户点击右上角收藏

1.4 组件生命周期

uni-app 组件支持的生命周期,与vue标准组件的生命周期相同。这里没有页面级的onLoad等生命周期:

函数名作用
beforeCreate在实例初始化之前被调用。
created在实例创建完成后被立即调用。
beforeMount在挂载开始之前被调用。
mounted挂载到实例上去之后调用。详见 注意:此处并不能确定子组件被全部挂载,如果需要子组件完全挂载之后在执行操作可以使用$nextTick
beforeUpdate数据更新时调用,发生在虚拟 DOM 打补丁之前
updated由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子
beforeDestroy实例销毁之前调用。在这一步,实例仍然完全可用
destroyedVue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。

1.5 路由跳转

  • uni.navigateTo 打开新页面 保留当前页面,跳转到应用内的某个页面
  • 参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔
  • 新页面入栈 页面跳转路径有层级限制,不能无限制跳转新页面
  • 跳转不了 tabBar 页面
uni.navigateTo({
	url: 'test?id=1&name=uniapp'
});
  • uni.switchTab Tab 切换 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
  • 页面全部出栈,只留下新的 Tab 页面
  • 跳转到 tabBar 页面只能使用 switchTab 跳转
  • 路径后不能带参数
uni.switchTab({
	url: '/pages/index/index'
});
  • uni.redirectTo 页面重定向 关闭当前页面,跳转到应用内的某个页面。
  • 当前页面出栈,新页面入栈
uni.redirectTo({
	url: 'test?id=1'
});
  • uni.navigateBack 页面返回
  • 页面不断出栈,直到目标返回页
  • 关闭当前页面,返回上一页面或多级页面。
  • 可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层。
// 注意:调用 navigateTo 跳转时,调用该方法的页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码

// 此处是A页面
uni.navigateTo({
	url: 'B?id=1'
});

// 此处是B页面
uni.navigateTo({
	url: 'C?id=1'
});

// 在C页面内 navigateBack,将返回A页面
uni.navigateBack({
	delta: 2
});
  • uni.reLaunch 重加载 关闭所有页面,打开到应用内的某个页面。
  • 页面全部出栈,只留下新的页面
uni.reLaunch({
	url: 'test?id=1'
});

1.6 页面通讯

$emit$on$off常用于跨页面、跨组件通讯

  • uni.$emit(eventName,OBJECT) 触发全局的自定义事件。附加参数都会传给监听器回调。
uni.$emit('update',{msg:'页面更新'})
  • uni.$on(eventName,callback) 监听全局的自定义事件。事件可以由 uni.$emit 触发,回调函数会接收所有传入事件触发函数的额外参数。
	uni.$on('update',function(data){
		console.log('监听到事件来自 update ,携带参数 msg 为:' + data.msg);
	})

  • uni.$once(eventName,callback) 监听全局的自定义事件。事件可以由 uni.$emit 触发,但是只触发一次,在第一次触发之后移除监听器。
  • uni.$off([eventName, callback]) 移除全局自定义事件监听器。

1.7 页面函数

  • getApp() 函数用于获取当前应用实例,一般用于获取globalData 。
const app = getApp()
console.log(app.globalData)
  • getCurrentPages() 函数用于获取当前页面栈的实例,以数组形式按栈的顺序给出,第一个元素为首页,最后一个元素为当前页面。
  • getCurrentPages()仅用于展示页面栈的情况,请勿修改页面栈,以免造成页面状态错误。

1.8 数据缓存

uni-appStorage在不同端的实现不同:

  • H5端为localStorage,浏览器限制5M大小,是缓存概念,可能会被清理
  • App端为原生的plus.storage,无大小限制,不是缓存,是持久化的
  • 各个小程序端为其自带的storage api,数据存储生命周期跟小程序本身一致,即除用户主动删除或超过一定时间被自动清理,否则数据都一直可用。
  • 微信小程序单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。
  • 支付宝小程序单条数据转换成字符串后,字符串长度最大200*1024。同一个支付宝用户,同一个小程序缓存总上限为10MB。

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

uni.setStorage({
	key: 'storage_key',
	data: 'hello',
	success: function () {
		console.log('success');
	}
});

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

try {
	uni.setStorageSync('storage_key', 'hello');
} catch (e) {
	// error
}

uni.getStorage(OBJECT) 从本地缓存中异步获取指定 key 对应的内容。

uni.getStorage({
	key: 'storage_key',
	success: function (res) {
		console.log(res.data);
	}
});

uni.getStorageSync(KEY) 从本地缓存中同步获取指定 key 对应的内容。

try {
	const value = uni.getStorageSync('storage_key');
	if (value) {
		console.log(value);
	}
} catch (e) {
	// error
}

uni.getStorageInfo(OBJECT) 异步获取当前 storage 的相关信息。

uni.getStorageInfo({
	success: function (res) {
		console.log(res.keys);
		console.log(res.currentSize);
		console.log(res.limitSize);
	}
});

uni.getStorageInfoSync() 同步获取当前 storage 的相关信息。

try {
	const res = uni.getStorageInfoSync();
	console.log(res.keys);
	console.log(res.currentSize);
	console.log(res.limitSize);
} catch (e) {
	// error
}

uni.removeStorage(OBJECT) 从本地缓存中异步移除指定 key。

uni.removeStorage({
	key: 'storage_key',
	success: function (res) {
		console.log('success');
	}
});

uni.removeStorageSync(KEY) 从本地缓存中同步移除指定 key。

try {
	uni.removeStorageSync('storage_key');
} catch (e) {
	// error
}

uni.clearStorage() 清理本地数据缓存。

uni.clearStorage();

uni.clearStorageSync() 同步清理本地数据缓存。

try {
	uni.clearStorageSync();
} catch (e) {
	// error
}

1.9 条件编译

条件编译是用特殊的注释作为标记,在编译时根据这些特殊的注释,将注释里面的代码编译到不同平台。

条件编译是利用注释实现的,在不同语法里注释写法不一样,js使用 // 注释、css 使用 /* 注释 */、vue/nvue 模板里使用 <!-- 注释 -->

  • #ifdef:if defined 仅在某平台存在
  • #ifndef:if not defined 除了某平台均存在
// #ifdef APP-PLUS
仅出现在 App 平台下的代码:
// #endif

// #ifndef H5
除了 H5 平台,其它平台均存在的代码
// #endif

// #ifdef H5 || MP-WEIXINH5 平台或微信小程序平台存在的代码(这里只有||,不可能出现&&,因为没有交集)
// #endif

%PLATFORM% 可取值如下:
在这里插入图片描述

2. 全局文件

2.1 App.vue

  • 入口文件,所有页面都是在App.vue下进行切换的
  • 作用:调用应用生命周期函数、配置全局样式、配置全局的存储globalData
  • 应用生命周期仅可在App.vue中监听,在页面监听无效

应用生命周期

函数名作用
onLaunch当uni-app 初始化完成时触发(全局只触发一次)
onShow当 uni-app 启动,或从后台进入前台显示
onHide当 uni-app 从前台进入后台
onError当 uni-app 报错时触发
	export default {
		onLaunch: function() {
			uni.getSystemInfo({
				success: function(e) {
					// #ifdef APP-PLUS
					// 检测升级
					appUpdate()
					// #endif
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight;
					if (e.platform == 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45;
					};
					// #endif

					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight;
					let custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.Custom = custom;
					Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif		

					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight;
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
					// #endif
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		}

	}
  • onReachBottom使用注意 可在pages.json里定义具体页面底部的触发距离onReachBottomDistance,比如设为50,那么滚动页面到距离底部50px时,就会触发onReachBottom事件。
  • 如使用scroll-view导致页面没有滚动,则触底事件不会被触发。scroll-view滚动到底部的事件请参考scroll-view的文档

globalData

小程序有globalData,这是一种简单的全局变量机制。这套机制在uni-app里也可以使用,并且全端通用。

  • js中操作globalData的方式如下: getApp().globalData.text = 'test'
  • 在应用onLaunch时,getApp对象还未获取,暂时可以使用this.globalData获取globalData。
  • 如果需要把globalData的数据绑定到页面上,可在页面的onShow页面生命周期里进行变量重赋值。
<script>  
    export default {  
        globalData: {  
            text: 'text'  
        }
    }  
</script>  

全局样式

在App.vue中,可以定义一些全局通用样式,例如需要加一个通用的背景色,首屏页面渲染的动画等都可以写在App.vue中。

注意如果工程下同时有vue和nvue文件,全局样式的所有css会应用于所有文件,而nvue支持的css有限,编译器会在控制台报警,提示某些css无法在nvue中支持。此时需要把nvue不支持的css写在单独的条件编译里。如:

<style>
    /* #ifndef APP-PLUS-NVUE */
    @import './common/uni.css';
    /* #endif*/
</style>

2.2 pages.json

用来对 uni-app 进行全局配置,决定页面文件的路径、窗口样式、原生的导航栏、底部的原生tabbar 等。

在这里插入图片描述

{
	"pages": [{
		"path": "pages/component/index",
		"style": {
			"navigationBarTitleText": "组件"
		}
	}, {
		"path": "pages/API/index",
		"style": {
			"navigationBarTitleText": "接口"
		}
	}, {
		"path": "pages/component/view/index",
		"style": {
			"navigationBarTitleText": "view"
		}
	}],
	"condition": { //模式配置,仅开发期间生效
		"current": 0, //当前激活的模式(list 的索引项)
		"list": [{
			"name": "test", //模式名称
			"path": "pages/component/view/index" //启动页面,必选
		}]
	},
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "演示",
		"navigationBarBackgroundColor": "#F8F8F8",
		"backgroundColor": "#F8F8F8",
		"usingComponents":{
			"collapse-tree-item":"/components/collapse-tree-item"
		},
		"renderingMode": "seperated", // 仅微信小程序,webrtc 无法正常时尝试强制关闭同层渲染
		"pageOrientation": "portrait", //横屏配置,全局屏幕旋转设置(仅 APP/微信/QQ小程序),支持 auto / portrait / landscape
		"rpxCalcMaxDeviceWidth": 960,
		"rpxCalcBaseDeviceWidth": 375,
		"rpxCalcIncludeWidth": 750
	},
	"tabBar": {
		"color": "#7A7E83",
		"selectedColor": "#3cc51f",
		"borderStyle": "black",
		"backgroundColor": "#ffffff",
		"height": "50px",
		"fontSize": "10px",
		"iconWidth": "24px",
		"spacing": "3px",
    	"iconfontSrc":"static/iconfont.ttf", // app tabbar 字体.ttf文件路径 app 3.4.4+
		"list": [{
			"pagePath": "pages/component/index",
			"iconPath": "static/image/icon_component.png",
			"selectedIconPath": "static/image/icon_component_HL.png",
			"text": "组件",
      		"iconfont": { // 优先级高于 iconPath,该属性依赖 tabbar 根节点的 iconfontSrc
       			"text": "\ue102",
        		"selectedText": "\ue103",
        		"fontSize": "17px",
        		"color": "#000000",
        		"selectedColor": "#0000ff"
      		}
		}, {
			"pagePath": "pages/API/index",
			"iconPath": "static/image/icon_API.png",
			"selectedIconPath": "static/image/icon_API_HL.png",
			"text": "接口"
		}],
		"midButton": {
			"width": "80px",
			"height": "50px",
			"text": "文字",
			"iconPath": "static/image/midButton_iconPath.png",
			"iconWidth": "24px",
			"backgroundImage": "static/image/midButton_backgroundImage.png"
		}
	},
  "easycom": {
    "autoscan": true, //是否自动扫描组件
    "custom": {//自定义扫描规则
      "^uni-(.*)": "@/components/uni-$1.vue"
    }
  },
  "topWindow": {
    "path": "responsive/top-window.vue",
    "style": {
      "height": "44px"
    }
  },
  "leftWindow": {
    "path": "responsive/left-window.vue",
    "style": {
      "width": "300px"
    }
  },
  "rightWindow": {
    "path": "responsive/right-window.vue",
    "style": {
      "width": "300px"
    },
    "matchMedia": {
      "minWidth": 768
    }
  }
}

2.3 manifest.json

manifest.json 文件是应用的配置文件,用于指定应用的名称、图标、权限等。

在这里插入图片描述

2.4 vue.config.js

vue.config.js 是一个可选的配置文件,如果项目的根目录中存在这个文件,那么它会被自动加载,一般用于配置 webpack 等编译选项

2.5 vite.config.js

vite.config.js 是一个可选的配置文件,如果项目的根目录中存在这个文件,那么它会被自动加载,一般用于配置 vite 的编译选项

2.6 uni.scss

uni.scss文件的用途是为了方便整体控制应用的风格。比如按钮颜色、边框风格,uni.scss文件里预置了一批scss变量预置。

/* 颜色变量 */

/* 行为相关颜色 */
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;

/* 文字基本颜色 */
$uni-text-color:#333;//基本色
$uni-text-color-inverse:#fff;//反色
$uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息
$uni-text-color-placeholder: #808080;
$uni-text-color-disable:#c0c0c0;

2.7 main.js

main.js是 uni-app 的入口文件,主要作用是初始化vue实例定义全局组件使用需要的插件vuex

import Vue from 'vue'
import App from './App'
import pageHead from './components/page-head.vue' //全局引用 page-head 组件

Vue.config.productionTip = false
Vue.component('page-head', pageHead) //全局注册 page-head 组件,每个页面将可以直接使用该组件
App.mpType = 'app'

const app = new Vue({
...App
})
app.$mount() //挂载 Vue 实例


使用Vue.use引用插件,使用Vue.prototype添加全局变量,使用Vue.component注册全局组件。

3. uni-app 实战

3.1 网络请求

1.在页面onLoad中调用请求函数,会在页面加载完成后调用。

2.请求前调用uni.showLoading方法

3.请求成功调用uni.hideLoading()方法

		data() {
			return {
				news: []
			}
		},
		onLoad() {
			uni.showLoading({
				title:"加载中...."
			});
			uni.request({
				url: 'https://unidemo.dcloud.net.cn/api/news',
				method: 'GET',
				data: {},
				success: res => {
					this.news = res.data;
					uni.hideLoading();
				},
				fail: () => {},
				complete: () => {}
			});
		},

3.2 模板语法

v-for 循环dom元素
@tap 绑定dom元素在小程序上的点击事件
:src启用双向数据绑定
{{item.title}} 模板语法

		<view class="uni-list">
			<view class="uni-list-cell" hover-class="uni-list-cell-hover" v-for="(item,index) in news" :key='index'
				@tap="openInfo" :data-postId="item.post_id">
				<view class="uni-media-list">
					<image class="uni-media-list-logo" :src="item.author_avatar"></image>
					<view class="uni-media-list-body">
						<view class="uni-media-list-text-top">{{item.title}}</view>
						<view class="uni-media-list-text-bottom uni-ellipsis">{{item.created_at}}</view>
					</view>
				</view>
			</view>
		</view>

3.3 打开页面

1.首先在pages.json创建新页面的路由

	"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
		{
			"path": "pages/index/index",
			"style": {
				"navigationBarTitleText": "news"
			}
		},
		{
			"path": "pages/info/info",
			"style": {
				"navigationBarTitleText": "info"
			}
		}
	],

2.编写跳转事件openInfo

		methods: {
			openInfo() {
				uni.navigateTo({
					url: '../info/info'
				});
			}
		}

3.在元素上绑定@tap点击事件

<view class="uni-list-cell" hover-class="uni-list-cell-hover" v-for="(item,index) in news" :key='index'
				// 微信小程序上的tap是点击事件
				@tap="openInfo">

3.4 页面传参

1.在元素上传递指定参数

<view class="uni-list-cell" hover-class="uni-list-cell-hover" v-for="(item,index) in news" :key='index'
				@tap="openInfo" 
				// 通过data-【参数】的形式来传递数据
				:data-postId="item.post_id">

2.在跳转事件上封装参数

		  	// 传递一个event事件,来获取元素上的数据
			openInfo(e) {
				let postid = e?.currentTarget?.dataset?.postid || '';
				console.log(postid);
				// 通过url拼接来传递参数
				uni.navigateTo({
					url: '../info/index?postid=' + postid,
				});
			}

3.在跳转页获取参数,通过props来获取

		onLoad(props) {
			if (props?.postid) {
				uni.request({
					url: 'https://unidemo.dcloud.net.cn/api/news/36kr/' + props?.postid,
					method: 'GET',
					data: {},
					success: res => {
						this.newitem = res.data
					},
					fail: () => {},
					complete: () => {}
				});
			}
		}

3.5 模拟直达效果

在pages.json中配置condition,可以在开发环境下每次修改项目直达指定的页面。

1.配置pages.json

	"condition": { //模式配置,仅开发期间生效
	    "current": 0, //当前激活的模式(list 的索引项)
	    "list": [
	        {
	            "name": "test", // 模式名称
	            "path": "pages/info/info", // 启动页面,必选
				"query":"postid=5310906" // 启动参数,在onLoad中获取
	        }
	    ]
	}

2.ctrl+r运行到test页面。
在这里插入图片描述

3.在模拟器上开启test模式。
在这里插入图片描述

3.6 创建tabBar

pages.json文件中设置tabBar属性即可生成tabBar

	"tabBar": {
		"color": "#7A7E83",
		"selectedColor": "#007AFF",
		"borderStyle": "black",
		"backgroundColor": "#F8F8F8",
		"list": [{
				"pagePath": "pages/home/index",
				"iconPath": "static/tabBar/home.png",
				"selectedIconPath": "static/tabBar/home-blue.png",
				"text": "主页"
			},
			{
				"pagePath": "pages/blog/index",
				"iconPath": "static/tabBar/document.png",
				"selectedIconPath": "static/tabBar/document-blue.png",
				"text": "博客"
			}, {
				"pagePath": "pages/resume/index",
				"iconPath": "static/tabBar/user.png",
				"selectedIconPath": "static/tabBar/user-blue.png",
				"text": "简历"
			}, {
				"pagePath": "pages/git/index",
				"iconPath": "static/tabBar/github-fill.png",
				"selectedIconPath": "static/tabBar/github-fill-blue.png",
				"text": "Git"
			}
		]
	}

3.7 引入组件

1.传统vue组件,需要安装引用注册,三个步骤后才能使用组件。

	// 引入方式统一以下面这种,只更换解构部分
	import {
		uniSearchBar
	} from '@dcloudio/uni-ui'

	export default {
		// 引入后进行组件注册,即可使用
		components: {
			uniSearchBar
		},
	}

2.easycom将其精简为一步。 只要组件安装在项目的components目录下,并符合components/组件名称/组件名称.vue目录结构。就可以不用引用、注册,直接在页面中使用。

3.8 子父组件传值

1.父组件通过强制数据绑定将自身的值传递给子组件。

<BlogList :news='news'/>

2.子组件通过props来获取父组件传递的值

	export default {
		props: {
			news: [],
		},
	}

3.子组件调用父组件的方法

// 父组件传递confirm给子组件
<YgSearchBar style="width: 100%;" placeholder="请输入搜索内容" @confirm='getCloudBlogList'/>

// 子组件通过this.$emit调用
this.$emit('confirm', e)

3.9 使用微信云开发

1.在app.js里面进行云开发的环境配置

		onLaunch: function() {
			wx.cloud.init({
				// env 参数说明:
				//   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
				//   此处请填入环境 ID, 环境 ID 可打开云控制台查看
				//   如不填则使用默认环境(第一个创建的环境)    
				//env: '你的环境ID',
				env: 'wx-yoga',
				traceUser: true,
			})
		},

2.查询表中所有数据

			// 获取云服务数据的方法
			getCloudBlogList() {
   				// 连接数据库
				const db = wx.cloud.database();
				// 执行查询操作
				db.collection('blog').get({
					success: res => {
						console.log(res.data);
						this.news = res.data;
					}
				});
			},

3.通过关键字进行模糊查询

					db.collection('blog').where({
						//使用正则查询,实现对搜索的模糊查询
						title: db.RegExp({
							regexp: e.value,
							//从搜索栏中获取的value作为规则进行匹配。
							options: 'i',
							//大小写不区分
						})
					}).get({
						success: res => {
							console.log(res.data);
							this.blogList = res.data;
							uni.hideLoading();
						}
					})

4.新增数据

const db = wx.cloud.database();
db.collection('todo').add({
	// data 字段表示需新增的 JSON 数据
	data: {
		status: 1,
		...formdata
	},
	success: function(res) {
		_this.getTodoList();
		_this.$refs.popup.close()
	}
})

5.根据id删除数据

const db = wx.cloud.database();
db.collection("todo").doc(articleId).remove();

6.根据id修改数据

const db = wx.cloud.database();
db.collection('todo').doc(this.selectValue._id)
	.update({
		data: {
			status: this.selectValue.status == 1 ? 2 : 1
		}
	}).then(res => {
		console.log('修改成功', res)
		//修改后刷新
		this.getTodoList('')
	}).catch(err => {
		console.log('修改失败', err)
	})

3.10 rich-text 显示富文本

显示markDown文件可以先将morkDown文件转换成html格式,再通过uni-app自带的rich-text显示

<rich-text :nodes="newitem.content"></rich-text>

3.11 web-view 实现嵌套网页

web-view 是一个 web 浏览器组件,可以用来承载网页的容器,会自动铺满整个页面(nvue 使用需要手动指定宽高)。

<web-view :src="newitem.content"></web-view>

3.12 使用watch监听状态变化

		watch: {
			tabIndex: {
				handler(v) {
					this.confirm();
				},
				deep: true
			}
		},

3.13 微信登录

1.使用 uni.getUserInfo 获取得到的 userInfo 为匿名数据,建议使用 uni.getUserProfile 获取用户信息。

<button class="sys_btn" @click="appLoginWx">小程序登录授权</button>

2.使用uni.getUserInfo获取基本信息

				uni.getUserProfile({
					desc: 'weixin',
					success: function(infoRes) {
						console.log(infoRes)
						_this.userInfo = infoRes.userInfo;
						_this.isCanUse = false;
						uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
						uni.hideLoading()
					},
					fail(res) {
						uni.showToast({
							title: "微信登录授权失败",
							icon: "none"
						});
						uni.hideLoading()
					}
				});

3.使用uni.setStorageSync(KEY,DATA)缓存登录信息

将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步api。

uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权

3.14 传入event,防止事件冒泡

1.点击事件传递event @click="onClick($event,'edit')"

2.阻止事件冒泡,使用@click.stop="onClick($event,'edit')"

3.15 引入echarts

  1. 引入 npm install echarts mpvue-echarts
  2. ECharts 在线构建 定制 echarts 的 js 文件
  3. 新建 common 文件夹,将定制文件放在 common 下
  4. 将 node_modules 下 mpvue-echarts 中 src 文件夹复制到 components 文件夹下
  5. 页面绘制
<!-- template -->
<view class="echarts-wrap">
	 <my-echarts id="mychart-dom-bar" canvas-id="mychart-bar" :echarts="echarts" :onInit="initChart"></my-echarts>
</view>
//script:
import * as echarts from '@/common/echarts.min.js';
import myEcharts from '@/components/src/echarts.vue';
export default {
	components:{myEcharts},
	data() {
		return {echarts}
	},
	methods: {
		initChart(canvas, width, height) {
			let chart = null
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				var option = {...}
				chart.setOption(option);
		 		return chart;
		}
	}
}

/*css*/
.echarts-wrap{
	width: 100%;
	height:500px;
}

  1. 遇到 this.echarts.setCanvasCreator is not a function 报错
在 components 下 src 中找到 echarts.vue文件
  1. 引入 import * as echarts from '@/common/echarts.min.js';
  2. 注销掉 props 中 echarts 对象
  3. 找到 this.ctx 和 const query ,给其添加 this 参数
  4. this.ctx = wx.createCanvasContext(canvasId,this);
  5. const query = wx.createSelectorQuery().in(this);
  1. 遇到 t.addEventListener is not a function 报错
在 common 中找到 echarts.min.js文件
  1. 全文搜索 use strict 在下面增加语句var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener
  2. 全文搜索 function Pe(t, e, n, i)function Le(t, e, n, i) 进行修改增加判断,(注意是参数中带有i的,Le 与 Pe 函数里内容可能颠倒,在原有方法上增加对应新判断即可)

3.16 秋云Ucharts

4. 生产发布

4.1 发布到微信小程序

1.配置AppID
AppID在小程序开发页面中的开发者设置中查看
在这里插入图片描述

2.打开微信开发者工具,在工具栏找到上传,填写版本号,发布。
在这里插入图片描述
3.上传成功之后,可以打开微信开发者管理后台,现在可以看到开发者的版本
在这里插入图片描述
4.然后指定小程序的主入口页,主要参照pages.json属性值pages数组的第一项的值

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值