uni-app introduction, conditional compilation, App-side Nvue development, HTML5+, development environment construction, custom components, configuration platform environment, uniCloud cloud development platform

Introduction to uni-app :

Overview: uni-app is a front-end cross-platform framework: if you know uni-app, you can use a set of code (similar to Vue syntax) to package Android, ios, and various small programs (WeChat, qq, Alipay, etc.) .

Ecology: Complete ecology, many third-party accesses only need simple configuration.

Advantages: a large number of developers, unlimited platform capabilities (supports native code mixing and native SDK integration), superior performance, rich surrounding ecology, low learning costs, and low development costs

Code style: Vue code development style is adopted as a whole, and Vue syntax is supported. The component label is close to the applet specification. When publishing h5, it supports all Vue syntax, and when publishing to APP and applet, it supports some Vue syntax.

The relationship between uni-app and vue and applets: Many hardware interfaces in vue do not support, but applets support, uni-app combines their respective advantages, the interface capability is close to the WeChat applet specification (wx is replaced by uni), and the overall code style Close to vue, on the basis of vue's life cycle, it also supports all wechat applet life cycles.

Support component-based development: Like Vue, it supports custom component development methods, which greatly improves development efficiency and fully conforms to software development ideas (high cohesion and low coupling).

uni-app specification: follow the vue single-file component (SFC) specification, data binding and event processing are the same as vue, in order to be compatible with multiple terminals, it is recommended to use flex layout.

Simple comparison between web code and uni-app:

<!-- web中标签写法: -->
<div class="main_box">
  <img src="logo.png" alt="">
  <p>
    <span>标题:xxx</span>
  </p>
</div>

<!-- uni-app中标签写法: -->
<view class="main_box">
  <image src="logo.png" alt=""></image>
  <view>
    <text>标题:xxx</text>
  </view>
</view>

Conditional compilation:
It is inevitable to encounter some compatibility problems in cross-platform development. At this time, if you write a lot of if-else, it will make the project difficult to maintain. Considering this, uni-app provides a conditional compilation method. The specific syntax is as follows:

#ifdef APP-PLUS
 写仅支持app下的代码块 
#endif

#ifdef H5
 写除h5平台以外平台的代码
#endif

#ifdef H5||MP-WEIXINH5或微信小程序代码块
#endif

App-side Nvue development:
Nvue is the abbreviation of nativeVue (the file with the suffix nvue), and has built-in weex rendering capability (Weex enables developers to use a Web-like syntax to build iOS, Android, and Web applications through a single code base). In Nvue, you can App that uses uni-app syntax and Weex to achieve native app experience.

HTML5+:
HTML5+ can provide us with direct calling of native Android and iOS plug-ins on the App side to solve certain functions that are difficult to implement in uni-app development, and has many built-in APIs to enrich development functions.

uni-app knowledge points:
components : custom components, basic components

API : Obtain network status, network requests, system information, etc.; navigation jump api, there is no vue-router in uni-app, but it is closer to page switching in applets.

Life cycle:
syntax : conditional judgment, list rendering, etc., layout style processing, use less/sass and other style preprocessors

The syntax of each .vue file in uni-app:

<template>
	<!-- v-bind动态绑定class事件名称,v-bind可以简写为冒号:,以及后面接数组或对象,语法和vue中一样,注意这里没有{
    
    {}} -->
	<view v-bind:class="className">
		<!-- 数据绑定:{
    
    {title}} -->
		<text class="title">{
   
   {title}}</text>
		<!-- v-on:事件绑定,v-on可以用@简写和vue中一样 -->
		<view v-on:click='clickHandle'>点我触发函数</view>
		<!-- v-if:条件渲染 -->
		<view v-if='false'>哈哈哈1</view>
		<view v-else>哈哈哈3</view>
		<view v-if='true'>哈哈哈2</view>
		<!-- v-for列表渲染: -->
		<view v-for='(item, index) in arr'>
			{
   
   {item}}{
   
   {index}}
		</view>
		<view v-for='(value, key) in obj'>
			{
   
   {key}}-{
   
   {value}}
		</view>
	</view>
</template>

<script>
	export default {
      
      
		// data初始化数据和vue中一样
		data() {
      
      
			return {
      
      
				title: 'Hello,my name is kuhai',
				className: 'active',
				arr: ['a','b','c'],
				obj: {
      
      a:1,b:2}
			}
		},
		onLoad() {
      
      

		},
		// 自定义方法写入的methods中和vue中一样
		methods: {
      
      
			clickHandle () {
      
      
				// 拿到状态中的某个值:this.变量名
				console.log(this.title)
				console.log('点击了我')
				// 改变状态中变量的值:this.变量名 = 值,和vue中一样
				this.title = 'how are you ?'
			}
		}
	}
</script>

<style>
	.active {
      
      
		background: skyblue;
	}
</style>

Development environment setup :
HbuiderX : HbuiderX editor has a very high support for uni-app, and it is recommended to use HbuiderX in uni-app development

Download and install HbuiderX : Go to the homepage of HbuiderX official website https://dcloud.io/, find the geek development tool and install it.
Please add a picture description
Create uni-app with vue-cli : In addition to creating uni-app projects by clicking the control panel in HbuilderX, you can also directly create uni-app projects through vue-cli. The difference is that the main code of the project created with vue-cli is in src Next, that is, the code under src is the same as the one created in HbuiderX (you can run the project by dragging the scr directory or the entire project directory into HbuiderX), the command:

vue create -p dcloudio/uni-preset-vue 自己uni-app项目名称

创建完项目可以在项目下继续使用命令 yarn serve 或在HbuiderX中运行项目,更多打包项目到各个平台可以参考package.json文件

Custom components:
exactly the same as in vue, just write according to vue syntax, but you need to create folders and component files according to the following directory structure:

├── api             // 统一接口目录
│   └── user.js     // 用户接口 (按功能分组)
├── common          // 公共目录
│   ├── common.js   // 公共函数 
├── components      // 公共组件目录,文件夹名称必须components,且必须存放到项目根目录下
├── pages           // 页面
│   ├── index
│   │   └── index.vue
│   ├── login      
│   │   ├── login.vue   
│   │   └── register    
├── static          // 静态资源 (css/js/图片/声音等等)
│   ├── images
│   │   ├── category.png
├── store           // vuex缓存
│   └── index.js
└── utils           // 工具目录
    └── request.js  // http请求库
├── App.vue         
├── main.js         // 入口文件
├── manifest.json   // uniapp配置文件
├── pages.json      // 页面配置
├── uni.scss        // 公共样式
├── README.md       // 自述文件

Right-click on the newly created components folder, and click on the top to directly create components, such as:
Please add a picture description

Configure the platform environment: (WeChat applet, app real machine (simulator), h5)
1. Wechat applet development environment configuration:

Open the native WeChat applet developer tools – top settings – security settings – service port open 21743

Open HbuiderX – Top Tools – Settings – Run Configuration – WeChat Developer Tools Path – Browse – find your own WeChat Developer Tools installation path, select the backend exe file (if you can’t select it, choose WeChat Developer Tools.exe folder)

2. Android development environment configuration:

Connect the Android phone to the computer with a data cable – phone settings – about the phone – click the version number 5 times to start developer debugging – turn on USB debugging – run HbuiderX – run to the phone or emulator –

uniCloud cloud development platform:

uniCloud is an official cloud development platform jointly with Alibaba Cloud and Tencent Cloud based on serverless mode and js programming. You can use js to easily develop back-end business, low development cost, mainly focus on business, do not need to pay attention to server operation and maintenance, etc., you can use the server without domain name if you do not publish non-h5 projects, uniCloud can solve the drawbacks that Tencent Cloud and Alibaba Cloud cannot cross-terminal.

uniCloud development process: create a uniapp project – choose a cloud development environment – ​​write back-end code in cloud functions – deploy the project to Ali or Tencent serverless environment – ​​call cloud functions from the client; use uniCloud cloud development performance can also be guaranteed, no need to worry Performance and O&M.

uniCloud composition:

Cloud functions: Cloud functions run in a customized node environment, have good performance and powerful functions, can execute js calculations, read and write nosql cloud databases, operate networks, and return data to the front end

'use strict';
  export.main = async (event, context) => {
    
    
    // event为客户端上传的参数
    console.log('event:' + event)
    // 返回数据给客户端:
    return event
  }

Cloud database: read the noSql-based json database in the cloud function, without learning SQL statements or understanding relational types

Cloud storage and CDN: CDN can be stored and operated in both the front-end and cloud functions, and the front-end can be directly transmitted to the CDN to avoid time-consuming server transfer bandwidth occupation, etc.

uniCloud cloud development environment configuration:

1. Create a new project in HbuiderX and select the uniCloud cloud development item—enter the project—right click on the uniCloud folder to select the associated cloud service space or project—the first time you enter, you need to create a new cloud server space (similar to a database)—create a good space After selecting and linking

2. After creating the cloud development space, continue to create cloud functions: right-click on the cloudfunctions folder under the uniCloud folder and select New Cloud Function/Cloud Object to create a cloud function—then there will be one more in the cloudfunctions folder The newly created cloud function folder - right-click the newly created cloud function folder and select upload deployment

Using the uniCloud web console:

1. Cloud function: Right-click the uniCloud folder under the project and select to open the uniCloud Web console—after entering, the currently selected cloud space (database) will be selected by default. At this time, you can click the home page in the upper left corner to see the one you created All cloud spaces—find the cloud space you created and click on the details to enter the cloud space—after entering the space, the left navigation will prompt cloud database cloud functions, etc., find the cloud function/cloud object and select the function/object list to see what you wrote cloud function

2. Cloud database: Find the cloud database in the navigation list - create a new table - continue to click to add records - write the standard JSON code in the right control panel and execute it, and a new data will be added

3. Cloud storage: It can store some files, such as pictures, etc. You can view pictures and other files in the details, and the files here can be accessed directly from the external network or used in projects.

Cross-domain configuration : The h5 project needs a domain name. At this time, cross-domain problems may occur. At this time, the domain name needs to be configured in the cross-domain configuration. After the domain name is configured, the cross-domain problem can be solved.

The cloud function in uniCloud connects to the database to realize addition, deletion, modification and query:

'use strict';
// 云函数类似node写的程序中的接口,login类似接口url,async (event, context)函数为接口处理函数,return类似response.send()

// 1.uniCloud.database()获取数据库引用:
const db = uniCloud.database()
exports.main = async (event, context) => {
    
    
	// context包含调用信息和服务器运行状态
	//event为客户端上传的参数
	console.log('event : ', event)
	// 2.db.collection(集合名称)获取集合引用,类似关系型数据库中的表,传入参数集合名称:数据库中的表:
	const userCollection = db.collection('user01')
	// 3.操作云数据库:
	// 3-1.userCollection.add()增加数据:里面可以传入一个个对象或一个数组JSON数据,返回插入数据的寄存器索引地址(执行完函数后可以到网页查看数据就会有记录)
	// let res1 = await userCollection.add({
    
    
	// 	'user_name': '00002',
	// 	'user_password': '22222'
	// })
	// console.log(JSON.stringify(res1))//{"id":"634a40dbb1fb07000109e6d4"}
	// let res2 = await userCollection.add([
	// 	{
    
    
	// 		'user_name': '00003',
	// 		'user_password': '33333'
	// 	},
	// 	{
    
    
	// 		'user_name': '00004',
	// 		'user_password': '44444'
	// 	}
	// ])
	
	// 3-2.userCollection.doc().remove()删除某条数据:,doc()表示根据数据id修改数据,这里还可以使用where({字段名:值})
	// let res3 = await userCollection.doc('634a40dbb1fb07000109e6d4').remove()
	// console.log(JSON.stringify(res3))//{"affectedDocs":1,"deleted":1}
	
	// // 3-3.userCollection.doc().update()修改某条数据:update可以使用set代替,区别:update不能更改不存在的数据,而set数据不存在就会自动增加一条
	// let res4 = await userCollection.doc('634a40db398d85000146b882').update({
    
    
	// 	user_name: '小红',
	// 	user_password: '123',
	// 	age: '18'
	// })
	// console.log(JSON.stringify(res4))//{"affectedDocs":1,"updated":1,"upsertedId":null}
	
	// 3-4.userCollection.doc().get()查找某条数据:
	let res5 = await userCollection.where({
    
    user_name: event.user_name}).get()
	console.log(JSON.stringify(res5))//{"affectedDocs":1,"data":[{"_id":"634a40db398d85000146b882","user_name":"小红","user_password":"123","age":"18"}]}
	//返回数据给客户端,这里可以将结果返回给函数调用者,也就是调用者回调函数success中参数
	return {
    
    
		cod:200,
		msg: '查询用户信息成功',
		data:res5.data
	}
};

Call the cloud function in the business to get the data:

<template>
	<view class="content">
		<image class="logo" src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-6890a278-1079-4fec-a0d9-0a94d7532a45/a9778618-cfd8-4017-aaa8-98d2a38768bf.jpg"></image>
		<view class="text-area">
			<text class="title">{
    
    {
    
    title}}</text>
		</view>
	</view>
</template>

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				title: 'Hello'
			}
		},
		onLoad() {
    
    
			// uniCloud.callFunction调用云函数api:
			uniCloud.callFunction({
    
    
				// name指定云函数名(自己在uniCloud下cloudfunctions中编写的函数):
				name:"login",
				// data:传入请求参数:
				data: {
    
    
					user_name: '小红'
				},
				// 成功后的回调:
				success (res) {
    
    
					console.log(res)
				},
				// 失败的回调:
				fail (err) {
    
    
					console.log(err)
				}
			})
			
		},
		methods: {
    
    

		}
	}
</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>

File upload read and delete:

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				title: 'Hello',
				imgUrl: null
			}
		},
		methods: {
    
    
			clickHandle () {
    
    
				const _this = this
				// 1.uni.chooseImage()选中图片api:
				uni.chooseImage({
    
    
					// 限制数量:
					count: 1,
					// 成功的回调,返回图表信息
					success (res) {
    
    
						// 拿到文件地址:res.tempFilePaths[0]
						const tempFile = res.tempFilePaths
						// 2.使用uniCloud.uploadFile()将文件上传到云储存,此api是云函数api应该放到云函数中,这里只是简单的测试:
						uniCloud.uploadFile({
    
    
							filePath: tempFile[0],
							// 设置云储存中文件名称,这里要设置,否则报错,特别是文件后缀,测试发现文件格式后缀和这里不匹配没关系,最终都会将自己定义的名称存到云储存
							cloudPath:String(Math.random()*5).split('.')[1] + '.png',
							success (res) {
    
    
								console.log(res)
								// res.fileID上传到云储存后的文件地址,可以将此地址存到某个表中后面通过此地址就可以访问到文件
								// res.filePath文件本地访问地址:
								_this.imgUrl = res.fileID
							},
							fail (err) {
    
    
								console.log(err)
							}
						})
					},
					// 失败的回调
					fail (err) {
    
    
						console.log(err)
					}
				})
				// 3.使用uniCloud.deleteFile()将文件从云储存中删除,这个必须放到云函数中去:
				uniCloud.deleteFile({
    
    
					// 要删除的文件地址:
					fileList: ['https://vkceyugu.cdn.bspapp.com/VKCEYUGU-6890a278-1079-4fec-a0d9-0a94d7532a45/a9778618-cfd8-4017-aaa8-98d2a38768bf.jpg']
					success (res) {
    
    
						console.log(res)
					},
					fail (err) {
    
    
						console.log(err)
					}
				})
			}
		}
	}
</script>

Tips: The pictures and other materials in this article come from the Internet. If there is any infringement, please send an email to the mailbox: [email protected] to contact the author to delete it.
Author: sea of ​​bitterness

Guess you like

Origin blog.csdn.net/weixin_46758988/article/details/128198296