search
HomeWeb Front-enduni-appLearn to use Vue in uni-app
Learn to use Vue in uni-appJan 19, 2021 am 09:44 AM
uni-appvue

Learn to use Vue in uni-app

Recommended (free): uni-app development tutorial

Article Directory

  • Foreword
  • 1. Use of properties and methods
  • 2. Vue life cycle
  • 3. Global variables
    • 1. Public module
    • 2. Mount Vue.prototype
    • 3.globalData
  • 4. Class and Style binding
    • 1. Object syntax
    • 2. Array syntax
  • Summary

Preface

The main content of this article is the usage of Vue in uni-app, as follows:
Vue supports responsive data operations, It can realize the binding of data and events, and supports this transfer;
uni-app adds application life cycle and page life cycle based on the Vue instance life cycle;
3 ways to implement global variables, namely Public modules, mounting Vue.prototype and globalData;
Dynamic binding of Class and Style, including the use of object syntax and list syntax.

1. Use of properties and methods

Vue is a progressive framework based on JavaScript for building user interfaces, supportingResponsive data operation, after declaring a variable, the view will be re-rendered after the value of the variable changes, without the need to manually update the DOM node.

As you can see, all page file suffixes are .vue, which is a single file. The variables are declared in the data attribute of the script module. templateWhen using variables in a block, you need to include the variable with {<!-- -->{}};
You can also define methods to perform specific functions, which need to be included in In the methods attribute of the script module, events can be bound in the component at the same time. The format is v-on:click="event name" and @click="event name", corresponding events can be triggered based on conditions.
For the correspondence between web events and events in uni-app, please refer to https://uniapp.dcloud.io/use?id=Event Processor.

index.vue is as follows:

<template>
	<view class="">
		<text>{{name}}</text>
		<button type="primary" @click="changeName">改变名字</button>
	</view></template><script>
	export default {
		data() {
			return {
				name: &#39;Corley&#39;
			}
		},
		onLoad() {
			
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeName: function(){
				this.name = &#39;Corlin&#39;
			}
		},
	}</script><style></style>

Among them, this represents the Vue instance itself. In addition to calling properties, you can also call methods.

Display:
uniapp vue data method basic

You can see that the name attribute has been changed.

If there are multiple functions nested in the function, there may be problems in passing this. In this case, you can use variables to replace , as follows:

<template>
	<view class="">
		<text>{{name}}</text>
		<button type="primary" @click="changeName">改变名字</button>
	</view></template><script>
	var _self;
	export default {
		data() {
			return {
				name: &#39;Corley&#39;
			}
		},
		onLoad() {
			_self = this
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeName: function(){
				_self.name = &#39;Corlin&#39;;
				setTimeout(function(){
					_self.name = &#39;Corlin...&#39;
				}, 2000);
			}
		},
	}</script><style></style>

Display:
uniapp vue data method this replace

You can see that after clicking the button, the name is changed first, and then changed again after 2 seconds, which means _self replaces this successfully.

2. Vue life cycle

Vue supports instance life cycle, uni-app adds application life cycle on this basis and Page life cycle.

Vue instance life cycle hook automatically binds this context to the instance, so you can access data and perform operations on properties and methods.
details as follows:

##beforeCreateAfter the instance is initialized, Data observer (data observer) and event/watcher event configuration are called before created is called immediately after the instance is created. At this step, the instance has completed the following configuration: data observer, property and method operations, and watch/event event callbacks. However, the mount phase has not started yet and the $el property is not yet available. beforeMountCalled before the mount starts: the related render function is called for the first time. mounted Called after the instance is mounted, then el is replaced by the newly created vm.$elbeforeUpdateCalled when the data is updated, which occurs before the virtual DOM is patched. This is suitable for accessing the existing DOM before updating, such as manually removing an added event listener. updatedThe virtual DOM is re-rendered and patched due to data changes, after which this hook will be calledactivatedCalled when a component cached by keep-alive is activateddeactivatedCalled when a component cached by keep-alive is deactivatedbeforeDestroyCalled before the instance is destroyed destroyedCalled after the instance is destroyed. After this hook is called, all instructions corresponding to the Vue instance are unbound, all event listeners are removed, and all child instances are destroyed. errorCapturedCalled when capturing an error from a descendant component. This hook receives three parameters: the error object, the component instance where the error occurred, and a string containing information about the source of the error. This hook can return false to prevent the error from propagating further upwards.
Function Meaning
The application life cycle belongs to the entire uni-app project and can only be monitored in App.vue. Monitoring on other pages is invalid.

The details are as follows:

FunctionMeaningonLaunchTriggered when uni-app initialization is completed (only triggered once globally)onShowWhen uni-app starts, or enters the foreground display from the backgroundonHideWhen uni-app enters the background from the front deskonErrorWhen uni-app reports an error Triggered whenonUniNViewMessageTo monitor the data sent by the nvue page, please refer to nvue communicating with vueonUnhandledRejection Listening function for unhandled Promise rejection event (2.8.1) onPageNotFound There is no listening function on the pageonThemeChangeMonitoring system theme changes
The page life cycle belongs to a specific page and is valid for the current page.

Common page life cycles are as follows:

FunctionMeaning onLoad monitors page loading, its parameter is the data passed on the previous page, and the parameter type is Object (used for page parameters), refer to the exampleonShowListen to the page display. Triggered every time the page appears on the screen, including returning from the lower-level page point to reveal the current pageonReadyListens for the completion of the initial rendering of the page. Note that if the rendering speed is fast, #onHide will be triggered before the page entry animation is completedonUnloadListen for page unloadingonResizeListen for window size changesonPullDownRefresh Monitor the user's pull-down action, generally used for pull-down refresh, refer to the example onReachBottomThe event when the page scrolls to the bottom (not scroll-view to the bottom), often used for pull-down Next page of data. See the notes below for detailsonPageScrollMonitor page scrolling, the parameter is ObjectonNavigationBarButtonTap Listen to the native title bar button click event, the parameter is Object

三、全局变量

uni-app中实现全局变量有几种实现方式。

1.公用模块

定义一个专用的模块,用来组织和管理这些全局的变量,同时将它们作为常量,在需要的页面引入,如果这些常量需要改变,直接在模块中改变即可,而不需要再在每一个导入的页面手动修改,优化了项目的结构。
例如,在 uni-app 项目根目录下创建 common 目录,然后在 common 目录下新建 constants.js 用于保存公共的变量和方法,一般为常量,很少需要改动,如下:

const apiUri = &#39;https://api.jisuapi.com/news/get?channel=头条&start=100&num=20&appkey=66487d31a1xxxxxx&#39;;const sayHi = function(){
	console.log(&#39;hello corley&#39;)}export default {
	apiUri,
	sayHi}

定义之后,需要通过export default导出,可以供其他页面导入使用。

再在index.vue中导入和使用:

<template>
	<view class="">
		<text>{{name}}</text>		
		<button type="primary" @click="changeName">改变名字</button>
		<text>{{link}}</text>
	</view></template><script>
	var _self;
	import common from &#39;../../common/constants.js&#39;
	export default {
		data() {
			return {
				name: &#39;Corley&#39;,
				link: &#39;&#39;
			}
		},
		onLoad() {
			_self = this;
			common.sayHi();
			this.link = common.apiUri		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeName: function(){
				_self.name = &#39;Corlin&#39;;
				setTimeout(function(){
					_self.name = &#39;Corlin...&#39;
				}, 2000);
			}
		},
	}</script><style></style>

显示:
uniapp vue global variable common

显然,实现了引用全局变量和方法。

2.挂载 Vue.prototype

将一些使用频率较高的常量或者方法,直接扩展到 Vue.prototype 上,每个 Vue 对象都会继承下来。
这种方式只支持vue页面,同时只需要在 main.js 中定义好即可在每个页面中直接调用。

先在项目的 main.js 中挂载属性或者方法,如下:

import Vue from &#39;vue&#39;import App from &#39;./App&#39;Vue.config.productionTip = false;Vue.prototype.appName = &#39;uni_demo&#39;;App.mpType = &#39;app&#39;const app = new Vue({
    ...App})app.$mount()

再在index.vue中调用即可,如下:

<template>
	<view class="">
		<text>{{name}}</text>		
		<button type="primary" @click="changeName">改变名字</button>
		<text>APP Name: {{app_name}}</text>
	</view></template><script>
	var _self;
	import common from &#39;../../common/constants.js&#39;
	export default {
		data() {
			return {
				name: &#39;Corley&#39;,
				app_name: &#39;&#39;
			}
		},
		onLoad() {
			_self = this;
			common.sayHi();
			this.app_name = this.appName		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeName: function(){
				_self.name = &#39;Corlin&#39;;
				setTimeout(function(){
					_self.name = &#39;Corlin...&#39;
				}, 2000);
			}
		},
	}</script><style></style>

显示:
uniapp vue global variable prototype

显然,成功导入了main.js中定义的变量。

3.globalData

对于小程序来说,还可以使用globalData属性在App.vue声明全局变量,同时支持H5、App等平台,是一种比较简单的全局变量使用方式。

App.vue如下:

<script>
	export default {
		globalData:{
			info: &#39;success&#39;
		},
		onLaunch: function() {
			console.log(&#39;App Launch&#39;)
		},
		onShow: function() {
			console.log(&#39;App Show&#39;)
		},
		onHide: function() {
			console.log(&#39;App Hide&#39;)
		}
	}</script><style>
	</style>

index.vue如下:

<template>
	<view class="">
		<text>{{name}}</text>		
		<button type="primary" @click="changeName">改变名字</button>
		<text>Status: {{status}}</text>
	</view></template><script>
	var _self;
	import common from &#39;../../common/constants.js&#39;
	export default {
		data() {
			return {
				name: &#39;Corley&#39;,
				status: &#39;failed&#39;
			}
		},
		onLoad() {
			_self = this;
			common.sayHi();
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeName: function(){
				_self.name = &#39;Corlin&#39;;
				_self.status = getApp().globalData.info;
				setTimeout(function(){
					_self.name = &#39;Corlin...&#39;
				}, 2000);
			}
		},
	}</script><style></style>

显示:
uniapp vue global variable globaldata

可以看到,获取到了App.vue中定义的全局变量globalData

除了前面3种方式,还可以通过Vuex实现,具体可参考https://ask.dcloud.net.cn/article/35021。

四、Class 与 Style 绑定

为节约性能,将 Class 与 Style 的表达式通过 compiler 硬编码到 uni-app 中,实现动态绑定class和style属性。

1.对象语法

可以传给 v-bind:class 一个对象,实现动态地切换 class;
也可以在对象中传入更多字段来实现动态切换多个 class。
v-bind:class 可以简写为:class,并且与普通的 class 共存。

index.vue如下:

<template>
	<view class="">
		<view :class="{active: isActive, fontSize50: isBig}">Hello Corley</view>		
		<button type="primary" @click="changeClass">改变名字</button>
	</view></template><script>
	var _self;
	import common from &#39;../../common/constants.js&#39;
	export default {
		data() {
			return {
				isActive: false,
				isBig: false
			}
		},
		onLoad() {
			_self = this;
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeClass: function(){
				_self.isActive = !_self.isActive;
				_self.isBig = !_self.isBig;
			}
		},
	}</script><style>
	.active {
		color: #DD524D;
	}
	.fontSize50 {
		font-size: 50upx;
	}</style>

显示:
uniapp vue class style object

可以看到,通过对象实现了动态切换class属性。

2.数组语法

可以把一个数组传给 v-bind:class,以应用一个 class 列表,列表的元素可以是变量、字符串、三元运算符或者对象,如下:

<template>
	<view class="">
		<view :class="[&#39;active&#39;, &#39;fontSize50&#39;]">江湖林野</view>		
		<view :class="[isActive?&#39;active&#39;:&#39;&#39;, fontCenter]">奇人异事</view>		
		<view :class="[{back: renderBack}, &#39;fontSize50&#39;]">飞贼走盗</view>		
		<button type="primary" @click="changeClass">改变class</button>
	</view></template><script>
	var _self;
	import common from &#39;../../common/constants.js&#39;
	export default {
		data() {
			return {
				isActive: true,
				isBig: false,
				fontCenter: &#39;fontCenter&#39;,
				back: &#39;back&#39;,
				renderBack: true
			}
		},
		onLoad() {
			_self = this;
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeClass: function(){
				_self.isActive = !_self.isActive;
				_self.isBig = !_self.isBig;
				_self.renderBack = !_self.renderBack;
			}
		},
	}</script><style>
	.active {
		color: #DD524D;
	}
	.fontSize50 {
		font-size: 50upx;
	}
	.fontCenter{
		text-align: center;
	}
	.back{
		background-color: #007AFF;
	}</style>

显示:
uniapp vue class style array

显然,实现了动态切换多个class。

style使用如下:

<template>
	<view class="">
		<view :class="[&#39;active&#39;, &#39;fontSize50&#39;]">江湖林野</view>		
		<view :class="[isActive?&#39;active&#39;:&#39;&#39;, fontCenter]">奇人异事</view>		
		<view :class="[{back: renderBack}, &#39;fontSize50&#39;]">飞贼走盗</view>		
		<view :style="[{ color: activeColor, fontSize: fontSize + &#39;px&#39; }]">神鬼传说</view>		
		<button type="primary" @click="changeClass">改变class</button>
	</view></template><script>
	var _self;
	import common from &#39;../../common/constants.js&#39;
	export default {
		data() {
			return {
				isActive: true,
				isBig: false,
				fontCenter: &#39;fontCenter&#39;,
				back: &#39;back&#39;,
				renderBack: true,
				fontSize: 60,
				activeColor: &#39;#3039dd&#39;
				
			}
		},
		onLoad() {
			_self = this;
		},
		onShow() {
		},
		onHide() {
		},
		methods: {
			changeClass: function(){
				_self.isActive = !_self.isActive;
				_self.isBig = !_self.isBig;
				_self.renderBack = !_self.renderBack;
				_self.fontSize = 30;
				_self.activeColor = &#39;#23A752&#39;
			}
		},
	}</script><style>
	.active {
		color: #DD524D;
	}
	.fontSize50 {
		font-size: 50upx;
	}
	.fontCenter{
		text-align: center;
	}
	.back{
		background-color: #007AFF;
	}</style>

显示:
uniapp vue class style style

可以看到,动态修改了行内样式。

总结

作为使用 Vue.js 开发前端应用的框架,uni-app中支持使用Vue语法,发布时也支持大部分甚至全部Vue的语法,在属性方法的使用、Class和Style的动态绑定等方面有很大的一致性,同时uni-app丰富了生命周期,增加了定义全局变量的方法,扩展了功能,有利于快速开发。

The above is the detailed content of Learn to use Vue in uni-app. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

VSCode中如何开发uni-app?(教程分享)VSCode中如何开发uni-app?(教程分享)May 13, 2022 pm 08:11 PM

VSCode中如何开发uni-app?下面本篇文章给大家分享一下VSCode中开发uni-app的教程,这可能是最好、最详细的教程了。快来看看!

利用uniapp开发一个简单的地图导航利用uniapp开发一个简单的地图导航Jun 09, 2022 pm 07:46 PM

怎么利用uniapp开发一个简单的地图导航?本篇文章就来为大家提供一个制作简单地图的思路,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

聊聊如何利用uniapp开发一个贪吃蛇小游戏!聊聊如何利用uniapp开发一个贪吃蛇小游戏!May 20, 2022 pm 07:56 PM

如何利用uniapp开发一个贪吃蛇小游戏?下面本篇文章就手把手带大家在uniapp中实现贪吃蛇小游戏,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version