uni-app study notes (2)

Table of contents

1. Routing and page jumps

1. Tabar and ordinary page jump examples

2、navigateTo

3、switchTab

2. vue components

1. Use of traditional vue components

2、easycom

3. uView component library

1. Installation and configuration

2. Introduce configuration

3. Use

4. Vuex

1. Get to know

2. Basic use of state

3. Use of mapState

5. Network requests

1. Encapsulation request

2. Refine the configuration of each interface

3. Instance call

6. Media upload pictures

1、uni.chooseImage(OBJECT)

2. Code examples


1. Routing and page jumps

1. Tabar and ordinary page jump examples

pages.json configuration page

{
	"pages": [{
			"path": "pages/about/about",
			"style": {
				"navigationBarTitleText": "关于",
				"enablePullDownRefresh": false
			}
		},
		{
			"path": "pages/index/index",
			"style": {
				"navigationBarTitleText": "首页"
			}
		}, {
			"path": "pages/prompt/prompt",
			"style": {
				"navigationBarTitleText": "提示框",
				"enablePullDownRefresh": false
			}
		}, {
			"path": "pages/swiper/swiper",
			"style": {
				"navigationBarTitleText": "滑块",
				"enablePullDownRefresh": false
			}
		}, {
			"path": "pages/form/form",
			"style": {
				"navigationBarTitleText": "表单",
				"enablePullDownRefresh": false
			}
		}, {
			"path": "pages/router/router",
			"style": {
				"navigationBarTitleText": "路由",
				"enablePullDownRefresh": false
			}

		}
	],
	"globalStyle": {
		"navigationBarTextStyle": "white",
		"navigationBarTitleText": "全局",
		"navigationBarBackgroundColor": "#000000",
		"backgroundColor": "#ffffff"
	},
	"tabBar": {
		"color": "#7A7E83",
		"selectedColor": "#1296db",
		"borderStyle": "black",
		"backgroundColor": "#000000",
		"list": [{
			"pagePath": "pages/index/index",
			"iconPath": "/static/首页2.png",
			"selectedIconPath": "/static/首页.png",
			"text": "首页"
		}, {
			"pagePath": "pages/about/about",
			"iconPath": "/static/关于2.png",
			"selectedIconPath": "/static/关于.png",
			"text": "关于"
		}, {
			"pagePath": "pages/form/form",
			"iconPath": "/static/表单 (1).png",
			"selectedIconPath": "/static/表单.png",
			"text": "表单"
		}, {
			"pagePath": "pages/router/router",
			"iconPath": "/static/路由器组2.png",
			"selectedIconPath": "/static/路由.png",
			"text": "路由"
		}]
	},
	"uniIdRouter": {}
}

router.vue file, simulate page jump

<template>
	<view>
		<button @click="toIndex">tabar跳转</button>
		<button @click="toSwiper">普通页面跳转</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			}
		},
		methods: {
			toIndex(){
				uni.switchTab({
					url:"/pages/index/index"
				})
			},
			toSwiper(){
				uni.navigateTo({
					url:"/pages/swiper/swiper"
				})
			}
		}
	}
</script>

2、navigateTo

(1) Jump to the url path of non-tabBar pages. The path can take parameters.

Format: path?key=value&key2=value2

path: the path to the page to jump to

toSwiper(){
	uni.navigateTo({
		url:"/pages/swiper/swiper?name=sxx"
	})
}

(2) Get parameters

Get it in the onLoad function of the page you jump to.

onLoad(option) {
	console.log(option);
},

3、switchTab

(1) Jump to the url path of the tabBar page (the page needs to be defined in the tabBar field of pages.json). The path cannot take parameters.

(2) The required parameters can be written to global variables to obtain


2. vue components

1. Use of traditional vue components

(1) Create components folder => Create .vue component file

(2) Introduce and register on the required page

index.vue

<template>
	<view class="content">
		<header-cpn></header-cpn>
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{
   
   {title}}</text>
		</view>
	</view>
</template>

<script>
	// 注意路径components前没有/
	// 命名至少两个词组成,以小驼峰的形式
	import headerCpn from 'components/header.vue'
	export default {
		components:{
			headerCpn
		},
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
			console.log(getApp().globalData);
		},
		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>

2、easycom

(1) Description

Traditional Vue components require installation, reference, and registration. The components can only be used after three steps.

easycom streamlines it into one step

(2) Use

As long as the component is installed in the components directory of the project and conforms to components/component name/component name.vue

Import it into the components file through the plug-in library and then import it directly.

DCloud plug-in marketDCloud plug-in marketicon-default.png?t=N7T8https://ext.dcloud.net.cn/ You can look at the file naming and documentation to decide the name of the imported tag


3. uView component library

1. Installation and configuration

(1) Open the engineering terminal

npm install [email protected]

If there is no package.json file in the root directory, execute the following command first

npm init -y

(2) uView relies on SCSS, and this plug-in must be installed, otherwise it will not function properly.

Check whether the scss plug-in is installed: Click Tools => Plug-in Installation

① Go to the plug-in market to install

②Terminal command installation

// 安装node-sass
npm i node-sass -D

// 安装sass-loader
npm i sass-loader -D

2. Introduce configuration

(1) Main JS library: In main.js in the project root directory, introduce and use uView’s JS library

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

Note that it should be placed afterimport Vue

(2) Global SCSS: Introduce uView theme files

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

(3) Introduce basic styles

is introduced in the first line of . Please add lang="scss" to the style tag. ;PropertiesApp.vue

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

(4) Configure easycom component mode

In the project root directorypages.json, configure easycom

Notice:

①Only oneeasycomfield

②After configuration, restart HX or recompile the project

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

3. Use

(1) Button

<template>
	<view>
		头部组件
		<u-button type="primary">主要按钮</u-button>
		<u-button type="success">成功按钮</u-button>
		<u-button type="info">信息按钮</u-button>
		<u-button type="warning">警告按钮</u-button>
		<u-button type="error">危险按钮</u-button>
	</view>
</template>


4. Vuex

1. Get to know

uni-app has Vuex built-in

(1) Usage scenarios

  • When a component needs to dispatch events multiple times. For example, adding or subtracting the quantity in the shopping cart.
  • Share data across components and across pages. For example, order status updates.
  • Data that needs to be persisted. For example, user information after login.
  • When you need to develop medium to large applications, suitable for complex multi-module multi-page data interaction, and consider how to better manage state outside the component

(2) Rules

  • Application-level state should be concentrated into a single store object.

  • Commit mutation is the only way to change the state, and the process is synchronous.

  • Asynchronous logic should be encapsulated into action 

2. Basic use of state

(1) In the project root directory, create a new store directory=》New index.js file

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state:{
        msg:'存放的信息'
    },
	mutations:{},
	actions:{},
	getters:{}
})
export default store

(2) Existing main.js Central entry

import store from './store'
const app = new Vue({
	store,
  ...App
})

(3) Obtain data

<template>
	<view>
		<button @click="toIndex">tabar跳转</button>
		<button @click="toSwiper">普通页面跳转</button>
		<text>{
   
   {$store.state.msg}}</text>
	</view>
</template>

3. Use of mapState

(1) When a component needs to obtain multiple states, it will be somewhat repetitive and redundant to declare these states as computed properties. In order to solve this problem, we can use the mapState auxiliary function to help us generate calculated properties

<template>
	<view>
		<text>{
   
   {$store.state.msg}}</text>
		<text>{
   
   {userName}}</text>
	</view>
</template>

<script>
	import { mapState } from 'vuex'//引入mapState
	export default {
		computed: mapState({
			// 从state中拿到数据 箭头函数可使代码更简练
			userName: state => state.userName,
		})
	}
</script>

(2) When the mapped calculated attribute name is the same as the child node name of state , you can pass a string array to mapState 

<template>
	<view>
		<text>{
   
   {$store.state.msg}}</text>
		<text>{
   
   {userName}}</text>
		<view>
			{
   
   {msg}}{
   
   {userName}}
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex'//引入mapState
	export default {
		computed: mapState(['msg','userName'])
	}
</script>


5. Network requests

Here the editor uses Tianxing API as an example

Tianxing Data TianAPI - Developer API Data Platform

1. Encapsulation request

Create utils folder => Create request.js file

const instance = (url,data,header,callback) => {
	const BASE_URL = "https://apis.tianapi.com"
	uni.request({
		url: BASE_URL + url,
		data,
		header,
		success: callback
	});
}
export default instance;

2. Refine the configuration of each interface

import instance from "../utils/request.js"

// 获取用户信息(GET)
export function getTianGou(data,callback){
	return instance(
		'/tiangou/index',
		data,
		{},
		callback
	)
}

3. Instance call

<script>
	import {
		getTianGou
	} from "../../api/user.js"
	import instance from "../../utils/request.js"
	export default {
		onLoad() {
            // 跳过第2步,直接调用
			instance("/tiangou/index", {
					key: ''//data传参
				}, {}, (res) => {
					console.log(res);
				}),
            // 细化接口配置后的调用
			getTianGou({
					key: ''//data传参
				}, (res) => {
					console.log(res);
				})
		},
	}
</script>


6. Media upload pictures

1、uni.chooseImage(OBJECT)

Parameter introduction:

①count: The maximum number of pictures that can be selected, default 9

②sizeType: original original image, compressed compressed image, both are available by default

uni.chooseImage({
	count: 6, //默认9
	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
	sourceType: ['album'], //从相册选择
	success: function (res) {
		console.log(JSON.stringify(res.tempFilePaths));
	}
});

2. Code examples

<template>
	<view>
		<!-- 媒体图片 -->
		<button type="default" @click="upImage">上传图片</button>
		{
   
   {imgArr}}
		<image v-for="item in imgArr" :key="item" :src="item" mode=""></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgArr:[]
			}
		},
		methods: {
			// 上传图片事件
			upImage(){
				uni.chooseImage({
					count:6,
					success:res=> {
						console.log(res.tempFilePaths);
						console.log(this.imgArr);
						this.imgArr = res.tempFilePaths
					}
				})
			}
		}
	}
</script>

Guess you like

Origin blog.csdn.net/qq_51478745/article/details/134229293