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. template
When 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: 'Corley'
}
},
onLoad() {
},
onShow() {
},
onHide() {
},
methods: {
changeName: function(){
this.name = 'Corlin'
}
},
}</script><style></style>
Among them, this
represents the Vue instance itself. In addition to calling properties, you can also call methods.
Display:
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: 'Corley'
}
},
onLoad() {
_self = this
},
onShow() {
},
onHide() {
},
methods: {
changeName: function(){
_self.name = 'Corlin';
setTimeout(function(){
_self.name = 'Corlin...'
}, 2000);
}
},
}</script><style></style>
Display:
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:
Function |
Meaning |
##beforeCreate | After 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. |
beforeMount | Called 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.$el |
beforeUpdate | Called 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. |
updated | The virtual DOM is re-rendered and patched due to data changes, after which this hook will be called |
activated | Called when a component cached by keep-alive is activated |
deactivated | Called when a component cached by keep-alive is deactivated |
beforeDestroy | Called before the instance is destroyed |
destroyed | Called 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. |
errorCaptured | Called 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. |
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:
Function | Meaning |
onLaunch | Triggered when uni-app initialization is completed (only triggered once globally) |
onShow | When uni-app starts, or enters the foreground display from the background |
onHide | When uni-app enters the background from the front desk |
onError | When uni-app reports an error Triggered when |
onUniNViewMessage | To monitor the data sent by the nvue page, please refer to nvue communicating with vue |
onUnhandledRejection | Listening function for unhandled Promise rejection event (2.8.1) |
onPageNotFound | There is no listening function on the page |
onThemeChange | Monitoring 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:
Function | Meaning |
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 example |
onShow | Listen 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 page |
onReady | Listens 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 completed |
onUnload | Listen for page unloading |
onResize | Listen for window size changes |
onPullDownRefresh | Monitor the user's pull-down action, generally used for pull-down refresh, refer to the example |
onReachBottom | The 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 details |
onPageScroll | Monitor page scrolling, the parameter is Object |
onNavigationBarButtonTap | Listen to the native title bar button click event, the parameter is Object |
三、全局变量
uni-app中实现全局变量有几种实现方式。
1.公用模块
定义一个专用的模块,用来组织和管理这些全局的变量,同时将它们作为常量,在需要的页面引入,如果这些常量需要改变,直接在模块中改变即可,而不需要再在每一个导入的页面手动修改,优化了项目的结构。
例如,在 uni-app 项目根目录下创建 common 目录,然后在 common 目录下新建 constants.js 用于保存公共的变量和方法,一般为常量,很少需要改动,如下:
const apiUri = 'https://api.jisuapi.com/news/get?channel=头条&start=100&num=20&appkey=66487d31a1xxxxxx';const sayHi = function(){
console.log('hello corley')}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 '../../common/constants.js'
export default {
data() {
return {
name: 'Corley',
link: ''
}
},
onLoad() {
_self = this;
common.sayHi();
this.link = common.apiUri },
onShow() {
},
onHide() {
},
methods: {
changeName: function(){
_self.name = 'Corlin';
setTimeout(function(){
_self.name = 'Corlin...'
}, 2000);
}
},
}</script><style></style>
显示:
显然,实现了引用全局变量和方法。
2.挂载 Vue.prototype
将一些使用频率较高的常量或者方法,直接扩展到 Vue.prototype 上,每个 Vue 对象都会继承下来。
这种方式只支持vue页面,同时只需要在 main.js 中定义好即可在每个页面中直接调用。
先在项目的 main.js 中挂载属性或者方法,如下:
import Vue from 'vue'import App from './App'Vue.config.productionTip = false;Vue.prototype.appName = 'uni_demo';App.mpType = 'app'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 '../../common/constants.js'
export default {
data() {
return {
name: 'Corley',
app_name: ''
}
},
onLoad() {
_self = this;
common.sayHi();
this.app_name = this.appName },
onShow() {
},
onHide() {
},
methods: {
changeName: function(){
_self.name = 'Corlin';
setTimeout(function(){
_self.name = 'Corlin...'
}, 2000);
}
},
}</script><style></style>
显示:
显然,成功导入了main.js中定义的变量。
3.globalData
对于小程序来说,还可以使用globalData
属性在App.vue声明全局变量,同时支持H5、App等平台,是一种比较简单的全局变量使用方式。
App.vue如下:
<script>
export default {
globalData:{
info: 'success'
},
onLaunch: function() {
console.log('App Launch')
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
}
}</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 '../../common/constants.js'
export default {
data() {
return {
name: 'Corley',
status: 'failed'
}
},
onLoad() {
_self = this;
common.sayHi();
},
onShow() {
},
onHide() {
},
methods: {
changeName: function(){
_self.name = 'Corlin';
_self.status = getApp().globalData.info;
setTimeout(function(){
_self.name = 'Corlin...'
}, 2000);
}
},
}</script><style></style>
显示:
可以看到,获取到了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 '../../common/constants.js'
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>
显示:
可以看到,通过对象实现了动态切换class属性。
2.数组语法
可以把一个数组传给 v-bind:class
,以应用一个 class 列表,列表的元素可以是变量、字符串、三元运算符或者对象,如下:
<template>
<view class="">
<view :class="['active', 'fontSize50']">江湖林野</view>
<view :class="[isActive?'active':'', fontCenter]">奇人异事</view>
<view :class="[{back: renderBack}, 'fontSize50']">飞贼走盗</view>
<button type="primary" @click="changeClass">改变class</button>
</view></template><script>
var _self;
import common from '../../common/constants.js'
export default {
data() {
return {
isActive: true,
isBig: false,
fontCenter: 'fontCenter',
back: 'back',
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>
显示:
显然,实现了动态切换多个class。
style使用如下:
<template>
<view class="">
<view :class="['active', 'fontSize50']">江湖林野</view>
<view :class="[isActive?'active':'', fontCenter]">奇人异事</view>
<view :class="[{back: renderBack}, 'fontSize50']">飞贼走盗</view>
<view :style="[{ color: activeColor, fontSize: fontSize + 'px' }]">神鬼传说</view>
<button type="primary" @click="changeClass">改变class</button>
</view></template><script>
var _self;
import common from '../../common/constants.js'
export default {
data() {
return {
isActive: true,
isBig: false,
fontCenter: 'fontCenter',
back: 'back',
renderBack: true,
fontSize: 60,
activeColor: '#3039dd'
}
},
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 = '#23A752'
}
},
}</script><style>
.active {
color: #DD524D;
}
.fontSize50 {
font-size: 50upx;
}
.fontCenter{
text-align: center;
}
.back{
background-color: #007AFF;
}</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!