uni-app + uniCloud Getting Started and Advanced

uni-app + uniCloud Getting Started and Advanced
Introduction
1. Basic knowledge of uni-app
1. Overview of uni-app core knowledge
2. Building a uni-app development environment
(1) Use vue-cli to run the project (not recommended)
(2 ) Install and run HBuilderX
3. Grammar knowledge
(1) Template syntax and data binding
(2) Conditional judgment (v-if, v-else-if, v-else)
(3) List rendering (v-for... in)
(4) Use of basic components
(5) Use of custom components
(6) Usage of basic API
(7) Conditional compilation
(8) Page layout
4. Life cycle
2. Basic configuration of uni-app
1. WeChat applet
2. App real machine, simulator
(1) App real machine
(2) Simulator (for Mac computer)
3. H5
4. Overview of uni-app directory structure
5. Configuration project bottom tab (pages.json)
6. In uni- How to use Sass in app
(1) Install plug-in
(2) Use of Sass plug-in
3. Basic usage of uniCloud
1. Get to know uniCloud
2. Configure uniCloud in HBuilderX
3. Use uniCloud's Web console
4. Cloud functions
5, cloud database
6, cloud storage
4. Comprehensive improvement of knowledge
1. Single file component
2. Global configuration and page configuration
3. Data binding
4 ,
5. Practical projects
1. Initialize the cloud database
2. Associate the page to the tabBar
3. Customize the navigation bar
4. Use font icons
5. Encapsulate network requests
6. Click the tab to switch content
7. Implement collection
8. Search logic Implementation
9. Tag page implementation logic
10. Rich text rendering
11. Comment content implementation logic
12. Association between collections and home page content
13. Follow and like
14. Feedback content and image upload
6. Project optimization and platform compatibility
7. Project packaging Release with
Summary
Introduction
What is uni-app:

uni-app is a framework developed by DCloud using Vue.js technology to develop all front-end applications.
uni-app can develop a set of codes to publish multiple platforms
. uni-app has a complete ecosystem and is favored by enterprises.
What are the advantages of uni-app:

The largest number of developers/cases
The platform’s capabilities are not limited: while crossing terminals, through conditional compilation + platform-specific API calls, you can elegantly write personalized code for the platform and call proprietary capabilities without affecting other platforms; support native code mixing Written and native SDK integration,
excellent performance experience
, rich surrounding ecology: supports small program components and SDK, compatible with mpvue components and projects, compatible with weex components; various SDKs in the WeChat ecosystem can be directly used in cross-platform APPs. Low learning cost: based on universal front-end
technology Stack, using vue syntax + WeChat applet API
development cost is low.
What is the relationship between uni-app and vue:

Developed using Vue.js syntax.
When publishing to H5, all Vue syntax is supported.
When publishing to Apps and applets, some Vue syntax is implemented.
What is the relationship between uni-app and applets:

Component tags are close to mini program specifications.
Interface capabilities (JS API) are close to WeChat mini program specifications.
Complete mini program life cycle
uni-app tips:

Generally, vue projects need to introduce and register when using page components. In uni-app, there is no need to introduce and register because of the easyCom function (local introduction). As long as the structure of the new component is components/component name/component name.vue can be
in Customize scss variables in the uni.scss file
1. Basic knowledge of uni-app
uni-app official website address: https://uniapp.dcloud.io/component/README
1. Overview of uni-app core knowledge
uni-app specifications:

The page file follows the Vue Single File Component (SFC) specification
// Template block: A page can only have one


{ {content}}


// Script block: A page can only have one

// Style block: there can be multiple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
component tags are close to the applet specification
// ordinary web development

// ni-app






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Interface capabilities (JS API) are close to the WeChat applet specification
onLoad() { // Get the network type uni.getNetWorkType() } 1 2 3 4 Data binding and events The processing is the same as Vue.js specification. In order to be compatible with multi-end operation, it is recommended to use flex layout for development ni-app features:









Conditional compilation
Conditional compilation writing instructions
#ifdef APP-PLUS Code that requires conditional compilation #endif Code that only appears under the App platform
#ifdef H5 Code that requires conditional compilation #endif Code that exists on other platforms except the H5 platform
#ifdef H5 | | MP-WEIXIN Code that requires conditional compilation #endif Code that exists on the H5 platform or WeChat mini program platform
Nvue on the App side develops
HTML5+
uni-app Knowledge points:

Component
Basic component
Custom component
Life cycle
API
routing: uni-app has no concept of routing, just page switching
Syntax
Layout style
2. Build uni-app development environment
(1) Use vue-cli to run the project (not recommended)
Install first There is node, and there are many tutorials on installing node online
// Check whether node is installed successfully
node -v
1
2
Install vue scaffolding
npm install @vue-cli -g
// or npm install @vue/cli -g

// Check whether vue-cli is installed successfully
vue -V
1
2
3
4
5
Install the uni-app project: first enter the directory to be installed
vue create -p dcloudio/uni-preset-vue project name
1
and then select the corresponding one by using the up and down keys on the keyboard "Template", press Enter to
run the project
// cd enter the project directory
cd project name

// Run the project
npm run serve
1
2
3
4
5
(2) Install and run HBuilderX
HBuilderX official website download address: https://www.dcloud.io/hbuilderx.html
When downloading, it is recommended to select the "App Development Version" corresponding to the system

After opening HBuilderX, create a new project and select uni-app, then fill in the "Project Name" and "Project Path", and select the corresponding "Template" to create a new uni-app project.

3. Grammar knowledge
(1) Template syntax and data binding
Template syntax: use double curly braces "{ { bound variables}}"
Data binding: use double curly braces "{ { bound variables}}" and data () {} The return {} data in the function is bound.
Dynamic binding: Use the v-bind instruction to bind the attribute to be bound (v-bind abbreviation: ":")
Two-way binding: Use the v-model instruction

hello uni-app

1
2
3
Binding event: Use the v-on instruction (v-on abbreviation: "@")
to modify the value of the variable
// In the WeChat applet
this.setData({ title: "hello" }) // In uni-app // this points to the current vue instance this.title = “hello” 1 2 3 4 5 6 7 Why data is written in the form of a function instead of an object:












If you use the object form, the variable will retain the last value when running the project and will not be initialized.
Using the function form can ensure that the variable value will be refreshed every time you enter the page, and will not be affected by the previous time
// Object form
data: { “name”: “hello world” }

// Function form
data() { return { name: “hello world” } } 1 2 3 4 5 6 7 8 9 10 11 (2) Conditional judgment (v-if, v-else-if, v-else) Determine whether a certain element or block of elements should be rendered v-if If the expression returns a value of true, the content will be rendered normally uni-app vue hello world 1 2 3 4 5 (3) List rendering (v-for… in ) Render the list through the array v-for … in render the list, item is the alias of the array element being iterated, index is the alias of the array subscript { { item }} 1 2 3 Render the list through the object v-for … in render the list, key is an alias for the key of the object being iterated, value is an alias for the value of the object, and index is an alias for the object index.








































{ {key}} = { {value}} = { {index}}

1
2
3
(4) Use of basic components
uni-app official website component address: https://uniapp.dcloud.io/component/README
view container component :,,, etc.
Basic content components:
Form components:, etc.
(5) Use of custom components
(6) Usage of basic API
API address: https://uniapp.dcloud.io/api/request/request
Initiate a request: uni.request()
uni.request( {
url: 'https://www.example.com/request',
data: {
text: 'uni.request'
},
header: {
'custom-header': 'hello' //Custom request header information
},
success: (res) => {
console.log(res.data);
this.text = 'request success';
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
上传
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
uni.uploadFile({
url: ‘https://www.example.com/upload’,
filePath: tempFilePaths[0],
name: ‘file’,
formData: {
‘user’: ‘test’
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
}
});
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16Download const downloadTask = uni.downloadFile({ url: 'http://www.example.com/file/test', success
: (res) => { if (res.statusCode === 200) { console.log('Download successful'); } } });







downloadTask.onProgressUpdate((res) => { console.log('Download progress' + res.progress); console.log('Downloaded data length' + res.totalBytesWritten); console.log('Expected to download Total data length' + res.totalBytesExpectedToWrite);


// 测试条件,取消下载任务。
if (res.progress > 50) {
    downloadTask.abort();
}

});
1
2 3
4
5
6
7 8 9 10 11 12 13 14 15 16 17 18 19 ( 7 ) Conditional compilation. For details, please refer to the official website: https://uniapp.dcloud.io/platform?id=Conditional compilation
is used Conditionally compiled code will only be compiled on the corresponding platform. Conditional compilation means writing the beginning and ending statements in the comment code. Comments are written differently in different syntaxes. js uses // comments and css uses /* comments* /. Using #ifdef in the vue/nvue template means that it will only be compiled on devices that meet the conditions; #ifndef means that it will not be compiled on devices that meet the conditions and will be compiled on other platforms.



















Indicates that this text is only compiled in H5

<!-- #ifndef H5 -->
<text>表示这段文本除了 H5 平台,其它平台都存在</text>
<!-- #endif -->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Conditional compilation writing instructions
Conditional compilation writing instructions
#ifdef APP-PLUS Code that requires conditional compilation #endif Code that only appears under the App platform
#ifndef H5 Code that requires conditional compilation #endif Code that exists on other platforms except the H5 platform
#ifdef H5 || MP-WEIXIN Code that requires conditional compilation #endif Code that exists on the H5 platform or WeChat mini program platform (here are only ||, && is not possible because there is no intersection)
conditionally compiled value and platform
Value Platform
APP-PLUS App
APP-PLUS-NVUE or APP-NVUE App nvue
H5 H5
MP-WEIXIN WeChat Mini Program
MP-ALIPAY Alipay Mini Program
MP-BAIDU Baidu Mini Program
MP-TOUTIAO ByteDance Mini Program
MP-QQ QQ Mini Program
MP-360 360 Mini Program
MP WeChat Mini Program/Alipay Mini Program/Baidu Mini Program/Bytedance Mini Program/QQ Mini Program/360 Mini Program QUICKAPP-WEBVIEW
Quick Application Universal (including Alliance, Huawei)
QUICKAPP-WEBVIEW-UNION Quick Application Alliance
QUICKAPP-WEBVIEW-HUAWEI Quick App Huawei
(8) Page Layout
There is no concept of body in uni-app. If you want to set a body-like style, use page

1
2
3
4
5
6
7
8
9
10
size units can be used: px, rem, Rex, vh, vw

1
2
3
4Introducing
external CSS

1
2
3
4. Life cycle.
For details about the life cycle, please see the official website: https://uniapp.dcloud.io/collocation/frame/lifecycle.
Application life cycle: defined in App.vue. For the complete application life cycle, please see the official website.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Page life cycle: defined in the page, see the official website for the complete page life cycle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 19 20 21 22
23
24
25 26 27 28 29 30 31 32 33 34 35 36 37 component life cycle, please see the official website for the complete component life cycle
















1
2
3
4
5
6 7
8
9
10
11
12
13
14 15 2. Basic configuration of uni-app 1. WeChat applet download WeChat developer tool address:
https://developers.weixin.qq.com/miniprogram/dev/ devtools/download.html First scan the QR code to open the WeChat developer tools, enter "Settings" -> "Security Settings", and then open the "Service Port"




Open HBuilderX, click "HBuilderX" -> "Preferences" in the upper left corner, "Settings.json" will open, click "Run Configuration", scroll down to find "Mini Program Run Configuration", click "Browse" on the right to find the developer Tool path (or manually fill in the developer tool path)

Run the project into the WeChat Developer Tools: Click the "Run Icon" in the picture below and select "WeChat Developer Tools". If a
compilation error occurs, you can close the WeChat Developer Tools and try again; or upgrade the WeChat Developer Tools to Latest stable version

2. App real machine, simulator
(1) App real machine
connects to Android devices (vivo is used below, other Android devices are similar):

Connect the phone to the computer with the data cable and
open the phone's "Settings" -> "About Phone" -> "Version Number (or Software Version Number)", click "Version Number" 5 times to enter developer mode, and wait until the phone prompts "You are already in development After entering "Developer Mode", return to the previous menu and enter "Developer Options", turn on the "USB debugging" switch (turn on "USB debugging", select "Transfer Files") and then you can run it to the mobile phone or simulator (the mobile phone during the process such
as You need to download HBuilder, just download and install it directly)

Connect ios device:

After the mobile phone and computer are connected through a data cable, also open HBuilderX -> "Run to mobile phone or simulator". As shown in the picture above, the position of the Android device information will display "Run - (Device: iPhone-iOS) - (uni-app-test" )"
if it does not display properly, you can download and install an iOS Mobile Assistant
(2) simulator (for Mac computers).
You can go to the App store to download an Xcode
and then open Xcode, click "Xcode" in the upper left corner -> "Preferences (System Preferences) " -> "Components", select the simulator version, install it.
After the installation is complete, restart HBuilderX, click the "Run icon" -> "Run - (Simulator: iPhone) - (uni-app-test)"
3.
Open HBuilderX on H5, Click "Preferences" -> "Run Configuration" -> "Browser Run Configuration" and fill in the installation path of the Chrome or Firefox browser.

Run: Click the "Run icon" and select "Chrome Run"

4. Overview of uni-app directory structure

.hbuilderx/launch.json file: Configures related settings when starting debugging.
Components directory: Folder used to store components. Custom components or components introduced from outside are placed in this directory.
Pages directory: Files used to store all pages. folder, which is equivalent to views in Vue development.
static directory: static file resource directory, such as storing images.
unpackaged/dist directory: compiled file storage directory. Some new project directories do not have this directory, but as long as it is compiled in WeChat developer tools, etc. After the platform is running, it will automatically generate
the utils directory: the public tool class directory
common directory: the public file directory
App.vue file: the page entry file
main.js file: the application entry file, which is mainly used to initialize the Vue instance and use the required Plug-in
manifest.json file: application configuration file, used to specify the name, icon, permissions, etc. of the application.
pages.json file: page configuration, which is a global configuration file that can configure the page path, window style, native navigation bar, and bottom Tab Column and other
uni.scss files: It is the style package of uni-app. You can quickly introduce the styles of the style package in other files. If you use Sass to develop, you can use the sass variables provided inside. 5. Configure the
bottom tab of the project (pages.json )
{ "pages": [ //The first item in the pages array represents the application startup page, reference: https://uniapp.dcloud.io/collocation/pages { "path": "pages/index/index",



"style": { "navigationBarTitleText": "uni-app" } } ], "globalStyle": { "navigationBarTextStyle": "black", "navigationBarTitleText": "uni-app", "navigationBarBackgroundColor": "#F8F8F8", “backgroundColor”: “#F8F8F8” }, “tabBar”: { “color”: “#7A7E83”, // The default color of the text on the tab “selectedColor”: “#3cc51f”, // The default color of the text on the tab when it is selected Color "borderStyle": "black", // The color of the upper border of the tabbar, the optional value is black/white "backgroundColor": "#ffffff", // The background color of the tab "list": [{ // The list of tabs, See the list attribute description for details, at least 2 and at most 5 tabs "pagePath": "pages/component/index", // The page path must be defined first in pages

















"iconPath": "static/image/icon_component.png", // Image path, the icon size is limited to 40kb, the recommended size is 81px * 81px, when the position is top, this parameter is invalid, network images are not supported, and fonts are not supported Icon
"selectedIconPath": "static/image/icon_component_HL.png", // Image path when selected
"text": "Component". // The text of the button on the tab is not required on App and H5 platforms. For example, you can put a + icon without text in the middle
}, { “pagePath”: “pages/API/index”, “iconPath”: “static/image/icon_API.png”, “selectedIconPath”: “static/image/icon_API_HL” .png", "text": "Interface" }] } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19


























20
21
22 23
24
25
26
27
28
29
30
31
32
33 6. How to use Sass in uni-app
( 1) Install plug- in Open HBuilderX, click "Tools" -> "Plug-in Installation"


"Install new plug-in" -> "Go to plug-in market"

"Search" -> "Download"

Use HBuilderX to import plug-ins (requires registration and login)

(2) Use of Sass plug-ins.
Styles can be nested and
Sass variables
can be used to represent parent



content .


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
213.
Basic usage of uniCloud
1. Understanding uniCloud
uniCloud is a cloud-based platform provided by DCloud, Alibaba Cloud and Tencent Cloud for uni-app developers. Serverless mode and JS programming cloud development platform
uniCloud uses JavaScript to develop the overall front-end and back-end business, which is friendly to front-end developers.
uniCloud allows developers to only focus on business development and does not need to care about server operation and maintenance.
For non-H5, use the server
uniCloud without a domain name. constitute:

Cloud function,
cloud database
, cloud storage and CDN
2. Configure uniCloud in HBuilderX.
First register and log in to HBuilderX
to create a uni-app project, and check "Enable uniCloud", then check "Alibaba Cloud" or "Tencent Cloud" on the right

Click "manifest.json", find "Basic Configuration", and then obtain the "uni-app application identification"

Right-click "uniCloud" in the project and select "Associate Cloud Service Space or Project"

For those who are using uniCloud for the first time, select "New", then DCloud's cloud web page will open, and you can authenticate as required...

When purchasing a cloud server, beginners can purchase a free one. The free server can be used for free for one month.

After creating the cloud service space, right-click on "uniCloud" again and select "Associate Cloud Service Space or Project", then click on the cloud service number, and then click "Associate"

Finally, you can create a new cloud function in the "cloudfunctions" directory. Right-click on the newly created cloud function and you can also upload and deploy the cloud function.

3. Use the uniCloud Web console.
Right-click on the "uniCloud" directory and select "Open uniCloud Web Console" to open the uniCloud Web console.

Then you can operate cloud databases, cloud functions, cloud storage, etc.

4. Cloud function
Cloud function is a function running in the cloud (server side). Every time a cloud function is modified, it must be uploaded and deployed to take effect. The
parameter context uploaded for the client
contains call information and running status, and the context of each call is obtained.
'use strict';
exports.main = async (event, context) => { //event is the parameter uploaded by the client console.log('event: ', event)

//返回数据给客户端
return event

};
1
2
3
4
5
6
7
8
You can use uni.callFunction({}) in the page to call the cloud function
methods: { function name() { uniCloud.callFunction({ name: "Cloud function name", data: {} , success(res) {}, fail(err) {} }) } } 1 2 3 4 5 6 7 8 9 10 5. Cloud database uniCloud provides a document database in JSON format. Each piece of data in the database is json format objects, the database can have multiple collections. The data are all standard JSON codes, and the strings need to use double quotes. Due to security considerations, cloud database calls can only be made in cloud functions, and cannot be added, deleted, or modified on the client. , check In the cloud function, you can obtain the database reference through uniCloud.database()
























The reference of the collection can be obtained through the database reference.collection().
New data: collection.add()
Delete data: collection.doc('The ID of the record').remove()
Modify the data: collection.doc('The ID of the record').update() or collection.doc('ID of the record').set() update
(): Only records with existing IDs can be updated. Records with non-existent IDs can be updated unsuccessfully
set() ): If the record exists, update it; if it does not exist, add it.
Query data:
'use strict';

// Get the reference to the database
const db = uniCloud.database()

exports.main = async (event, context) => { // Get a reference to the collection const collection = db.collection('name of the collection')

// 新增数据
// 新增 1 条记录
let res1 = await collection.add({
	name: "zs"
})
// 新增 多 条记录
let res2 = await collection.add([
	{
		name: "lisi",
		age: 12
	},
	{
		name: "wangwu"
	}
])

// 删除记录
const res3 = await collection.doc('该条记录的ID').remove()

// 修改记录
const res4 = await collection.doc('该条记录的ID').update()
const res5 = await collection.doc('该条记录的ID').set()

// 查询记录
// 查询指定ID的记录
const res6 = await collection.doc('该条记录的ID').get()
// 查询指定字段的记录
const res6 = await collection.where(查询条件).get()

//返回数据给客户端
return event

} ;
1
2
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
20
22 22 26 27 28 29 32 33 33
36 37 38 39 40 41 _ _ _ _ _ _ _ All functions must be uploaded, deployed and tested on the page. Therefore, when operating the cloud function, you can directly "upload and run" the cloud function, and then view the test results on the console.




















6. Cloud storage
upload file
methods: { addImage() { let count = 9 - this.imageLists.length let that = this uni.chooseImage({ count: count, success(res) { const tempFilePaths = res.tempFilePaths tempFilePaths.forEach ((item, index) => { // Handle H5 multi-select status if (index < count) { that.imageLists.push({ url: item }) } }) } }) },

















async submit() {
	let imagesPath = []
	// uni.showLoading()
	for (let i = 0; i < this.imageLists.length; i++) {
		const filePath = this.imageLists[i].url
		this.uploadFiles(filePath)
	}
},
async uploadFiles(filePath) {
	const result = await uniCloud.uploadFile({
		cloudPath: new Date(),
		filePath: filePath
	})
	return result.fileID
},

// 删除云存储中的文件
uniCloud.deleteFile({
	fileList: ['云存储中的下载地址'],
	success(res) {
		console.log(res)
	},
	fail(err) {
		console.log(err)
	}
})

}
1
2
3
4
5 6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 28
29
30 31
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 4 . Comprehensive improvement of knowledge 1. Single file component




















uni-app is a full-end solution based on Vue. The development specification of uni-app page file follows the Vue single file component (SFC) specification. What is
Vue's single file component:

In Vue, every file ending with .vue is a single-file component.
Each single-file component mainly contains three major blocks:,
After creating a .vue file, vue-loader will parse the file and extract each Language modules, assemble them into a CommonJS module, which will export a component object by default.
Use uni-app to create a page:

In a new page, three modules of single-file components will be created by default.
Only a single root node is supported in the template (although Vue3 supports multiple root nodes), and the root tag is different from Vue, which uses

, and uni-app uses the
script module. Each .vue file can only contain a
style module within a tag. Unlike the script module, a .vue file can contain multiple tags, which
can be specified in the start tags of the three modules. The language can be specified by using the lang attribute, for example: lang="jade", lang="ts", lang="sass" 2.
Global configuration and page configuration
3. Data binding
4.
5. Practical projects
1. Initialization Cloud database
Create a new "db_init.json" file under uniCloud to initialize the cloud database

The data structure is as follows
{ "collection name": { // collection name (table name) "data": [ // data { "key": "value", "key": "value" }, { "key": " Value", "key": "value" } ] } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2. Associate the page to the tabBar. Enter the pages.json file and add the tabBar field { "pages": [ //The first item in the pages array represents the application startup page, reference: https://uniapp.dcloud.io/collocation/pages { “path”: “pages/tabbar/index/index”, “style”: { “navigationStyle ” ":"custom",



































“navigationBarTextStyle”:“white”,
“navigationBarTitleText”:“首页”
}
},
{
“path”: “pages/tabbar/follow/follow”,
“style”: {
“navigationBarTitleText”:“关注”
}

	}, 
	{
		"path": "pages/tabbar/my/my",
		"style": {
			"navigationBarTitleText":"个人中心"
		}
	}
],
"globalStyle": { // 设置全局样式
	"navigationBarTextStyle": "black",
	"navigationBarTitleText": "uni-app",
	"navigationBarBackgroundColor": "#F07373",
	"backgroundColor": "#F8F8F8"
},
"tabBar": {  // 设置页面底部的 tabBar,至少2,最多5
	"color": "#666",  // 默认(未选择时)颜色
	"selectedColor": "#f07373",  // 选择时的颜色
	"backgroundColor": "#fff",  // tabBar 背景色
	"list": [{
		"pagePath": "pages/tabbar/index/index", // 页面路径
		"text": "首页",  // tabBar 文字
		"iconPath": "static/home.png",  // 未选中时 tabBar 图标
		"selectedIconPath": "static/home-active.png" // 选中时 tabBar 图标
	}, {
		"pagePath": "pages/tabbar/follow/follow", // 页面路径
		"text": "关注",  // tabBar 文字
		"iconPath": "static/follow.png",  // 未选中时 tabBar 图标
		"selectedIconPath": "static/follow-active.png"  // 选中时 tabBar 图标
	}, {
		"pagePath": "pages/tabbar/my/my", // 页面路径
		"text": "我的",  // tabBar 文字
		"iconPath": "static/my.png",  // 未选中时 tabBar 图标
		"selectedIconPath": "static/my-active.png"  // 选中时 tabBar 图标
	}]
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

3. Customize the navigation bar.
Each page has a native navigation bar. If you need to customize it, you need to configure it in pages.json.
Set the value of navigationStyle in style to custom
{ "pages": [ //The first item in the pages array represents Application startup page, reference: https://uniapp.dcloud.io/collocation/pages { “path”: “pages/tabbar/index/index”, “style”: { “navigationStyle”: “custom”, “navigationBarTextStyle” ; _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Compile and set the height of the status bar























created() { // Get phone system information const phoneInfo = uni.getSystemInfoSync()

// 获得状态栏高度
this.statusBarHeight = phoneInfo.statusBarHeight
this.windowWidth = phoneInfo.windowWidth
		
// #ifndef H5 || APP-PLUS || MP-ALIPAY
// 获取胶囊的位置
const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
// console.log(menuButtonInfo)
		
// 导航栏高度 = (胶囊底部高度 - 状态栏高度) + (胶囊顶部高度 - 状态栏高度)
this.navbarHeight = (menuButtonInfo.bottom - phoneInfo.statusBarHeight) + (menuButtonInfo.top - phoneInfo.statusBarHeight)
		
// 导航栏宽度
this.windowWidth = menuButtonInfo.left
// #endif
		
// #ifdef MP-ALIPAY
this.statusBarHeight = 0
// #endif

},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
4. To use font icons,
you can use Ali’s vector library: https://www. iconfont.cn
can also be used in the DCloud plug-in market: https://ext.dcloud.net.cn/ Search icons and install the icons plug-in shown below.

Use icons: For the type value corresponding to the icon, see the example: https://hellouniapp.dcloud.net.cn/pages/extUI/icons/icons

1
5. Encapsulate network requests

index.js

// Batch export files

const requireApi = require.context(
// Relative path of api directory
'.',
// Whether to query subdirectories
false,
// Query file suffix
/.js$/
)

let module = {}

requireApi.keys().forEach((key,index) => {
if(key === ‘./index.js’) return

Object.assign(module, requireApi(key))

})

export default module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
list.js

import $http from ‘…/http.js’

export const get_label = (data) => {
return $http({
url: ‘get_label’,
data
})
}

export const update_label = (data) => {
return $http({
url: ‘update_label’,
data
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
http.js
import store from ‘…/store/index.js’

export default function $http(options) {
const { url, data } = options

const dataObj = {
	user_id: store.state.userInfo._id,
	...data
}

return new Promise((resolve, reject) => {
	uniCloud.callFunction({
		name: url,
		data: dataObj
	}).then(res => {
		if(res.result.code === 200) {
			resolve(res.result)
		} else {
			reject(res.result)
		}
	}).catch(err => {
		reject(err)
	})
})

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
6. Click on the tab to switch the content and
change color on click: click on the label, trigger the event, and change the index of the currently clicked label Assign the value to the variable in data, and then bind the class (:class="{active: activeIndex === index}"). If the default value is equal to the index value, activate the color-changing style to switch the content: click the label, trigger the event,
and The index of the currently clicked tag is triggered to the page that calls the component. After getting the index value, the page gets the tag name based on the index, and then queries the tag name to get the corresponding card content, which is rendered to the corresponding swiper content block <view class="



tab -scroll_item” :class="{active: activeIndex === index}" v-for="(item,index) in list" :key="index" @click="clickTab(item,index)">{ { item.name}}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 17 18 19 20 21 22 23 24 25 26 27 7. Implementation of collection Click the collection button
to trigger an event, invert the variable value in data, and update the database The value of the corresponding field <view class="icons" @click.stop="likeTab">














data() {
return {
like: false
};
},

methods: { likeTab() { this.like = !this.like this.setUpdateLikes() }, } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 8. Search logic implementation first uses v-model binding Set the search value, and use throttling (delay delay of 1 second) to bind the input value to the variables in data. At the same time, query the data in the database. Only by clicking on the content card obtained from the query will the input content be stored. into vuex, and then you can get the search history by introducing and deconstructing mapState import { mapState } from 'vuex' computed: { ...mapState(['historyList']) }, 1 2 3 4 The search history will also be carried out in vuex Persistent state: {

































historyList: uni.getStorageSync('__history') || []
},
1
2
3
9. Implementation logic of tab page
10. Rich text rendering
11. Implementation logic of comment content
12. Association between collections and homepage content
13. Follow and like
Follow the author simultaneously

14. Feedback content and image upload
6. Project optimization and platform compatibility
7. Project packaging and release
Summary
Project introduction:
——————————————
Copyright statement: This article is written by CSDN blogger "@ "lgk_Blog"'s original article follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement when reprinting.
Original link: https://blog.csdn.net/weixin_49809163/article/details/119121449

Guess you like

Origin blog.csdn.net/yang20000222/article/details/131157774