Home Web Front-end uni-app Learn to use Vue in uni-app

Learn to use Vue in uni-app

Jan 19, 2021 am 09:44 AM
uni-app vue

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>
Copy after login

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>
Copy after login

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.
FunctionMeaning
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}
Copy after login

定义之后,需要通过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>
Copy after login

显示:
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()
Copy after login

再在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>
Copy after login

显示:
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>
Copy after login

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>
Copy after login

显示:
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>
Copy after login

显示:
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>
Copy after login

显示:
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>
Copy after login

显示:
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles