Basic use of uni-app
uni-app Introduction Official Website
uni-app
It is a framework for developing all front-end applications using Vue.js. Developers write a set of codes that can be published to iOS, Android, H5, and various small programs (WeChat/Alipay/Baidu/Toutiao/QQ/DingTalk), etc. platform.
Even if it is not cross-terminal, uni-app
it is also a better framework for small program development.
Experienced in developing vue and WeChat applets, can quickly get started with uni-app
Why study uni-app?
Compared with developers, the cost of learning is reduced, because after only learning uni-app, you can develop applications for iOS, Android, H5, and various small programs, and you don’t need to learn the framework for developing other applications. As a result, the development cost is also greatly reduced.
Environment build
Install the editor HbuilderX download address
HBuilderX is a general-purpose front-end development tool, but uni-app
it has been specially enhanced.
Download the App development version, which can be used out of the box
Install WeChat Developer Tools Download link
Initialize the project with HbuilderX
-
Click HbuilderX menu bar File > Project > New
-
Select uni-app, fill in the project name, the directory created by the project
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-8bW1h2Dn-1677136476352)(./images/create.jpg)]
run project
Click Run in the menu bar, run to the browser, select the browser to run
Run in the WeChat developer tool: Enter the hello-uniapp project, click Run -> Run to Mini Program Simulator -> WeChat developer tool, and you can experience uni-app in the WeChat developer tool
Run in the WeChat developer tools: Enter the hello-uniapp project, click Run on the toolbar -> Run to mobile phone or emulator -> select the mobile phone of the mode
Notice:
- If it is the first time to use, you need to configure the relevant path of the ide of the applet before running successfully
- The WeChat developer tools are set securely in the settings, and the service port is opened
Introduce the role of project directory and files
pages.json
The file is used to configure uni-app globally, determine the path of the page file, window style, native navigation bar, native tabbar at the bottom, etc.
manifest.json
The file is the configuration file of the application, which is used to specify the name, icon, permissions, etc. of the application.
App.vue
It is our root component, all pages are switched App.vue
under it , and it is the page entry file, which can call the life cycle function of the application.
main.js
Is our project entry file, the main function is to initialize vue
the instance and use the required plug-ins.
uni.scss
The purpose of the file is to facilitate overall control over the style of the application. For example, button color, border style, and uni.scss
a batch of scss variable presets are preset in the file.
unpackage
It is the packaging directory, where there are packaging files for each platform
pages
All pages storage directory
static
Static resource directory, such as pictures, etc.
components
Component storage directory
In order to achieve multi-terminal compatibility, considering factors such as compilation speed and running performance, uni-app
the following development specifications are agreed:
- Page files follow the Vue Single File Component (SFC) specification
- The component label is close to the applet specification, see uni-app component specification for details
- The interface capability (JS API) is close to the WeChat applet specification, but the prefix needs to
wx
be replaceduni
, see uni-app interface specification for details - Data binding and event processing are the same as
Vue.js
the specification , while supplementing the life cycle of App and page - In order to be compatible with multi-terminal operation, it is recommended to use flex layout for development
Global configuration and page configuration
Global configuration via globalStyle
Used to set the status bar, navigation bar, title, window background color, etc. of the application. detailed documentation
Attributes | type | Defaults | describe |
---|---|---|---|
navigationBarBackgroundColor | HexColor | #F7F7F7 | Navigation bar background color (same as status bar background color) |
navigationBarTextStyle | String | white | Navigation bar title color and status bar foreground color, only support black/white |
navigationBarTitleText | String | Navigation bar title text content | |
backgroundColor | HexColor | #ffffff | background color of the window |
backgroundTextStyle | String | dark | Pull down the loading style, only support dark / light |
enablePullDownRefresh | Boolean | false | Whether to enable pull-down refresh, see page life cycle for details . |
onReachBottomDistance | Number | 50 | The distance from the bottom of the page when the page pull bottom event is triggered, the unit only supports px, see page life cycle for details |
Create a new message page
Right-click pages to create a new message directory, right-click to create a new .vue file under the message directory, and select the basic template
<template>
<view>
这是信息页面
</view>
</template>
<script>
</script>
<style>
</style>
Configure pages through pages
Attributes | type | Defaults | describe |
---|---|---|---|
path | String | Configure page path | |
style | Object | Configure page window performance, configuration items refer to pageStyle |
The first item in the pages array array represents the application startup page
"pages": [ 、
{
"path":"pages/message/message"
},
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app"
}
}
]
Modify the title and navigation bar background color of the page through style, and set the unique style of h5 pull-down refresh
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
{
"path":"pages/message/message",
"style": {
"navigationBarBackgroundColor": "#007AFF",
"navigationBarTextStyle": "white",
"enablePullDownRefresh": true,
"disableScroll": true,
"h5": {
"pullToRefresh": {
"color": "#007AFF"
}
}
}
}
]
configure tabbar
If the application is a multi-tab application, you can specify the performance of the tab bar and the corresponding page displayed when the tab is switched through the tabBar configuration item.
Tips
- When the position is set to top, the icon will not be displayed
- The list in the tabBar is an array, and only a minimum of 2 and a maximum of 5 tabs can be configured, and the tabs are sorted in the order of the array.
Property description:
Attributes | type | required | Defaults | describe | Explanation of Platform Differences |
---|---|---|---|---|---|
color | HexColor | yes | The default color of the text on the tab | ||
selectedColor | HexColor | yes | The color of the text on the tab when selected | ||
backgroundColor | HexColor | yes | background color of the tab | ||
borderStyle | String | no | black | The color of the upper border of the tabbar, only black/white is supported | App 2.3.4+ supports other color values |
list | Array | yes | The list of tabs, see the description of the list attribute for details, at least 2 and at most 5 tabs | ||
position | String | no | bottom | Optional values bottom, top | The top value is only supported by WeChat applets |
Among them, list receives an array, each item in the array is an object, and its attribute values are as follows:
Attributes | type | required | illustrate |
---|---|---|---|
pagePath | String | yes | Page path, must be defined first in pages |
text | String | yes | Button text on the tab, optional on 5+APP and H5 platforms. For example, a + icon without text can be placed in the middle |
iconPath | String | no | Image path, the icon size is limited to 40kb, the recommended size is 81px * 81px, when the postion is top, this parameter is invalid, does not support network images, does not support font icons |
selectedIconPath | String | no | The image path when selected, the icon size is limited to 40kb, the recommended size is 81px * 81px, when the postion is top, this parameter is invalid |
Case code:
"tabBar": {
"list": [
{
"text": "首页",
"pagePath":"pages/index/index",
"iconPath":"static/tabs/home.png",
"selectedIconPath":"static/tabs/home-active.png"
},
{
"text": "信息",
"pagePath":"pages/message/message",
"iconPath":"static/tabs/message.png",
"selectedIconPath":"static/tabs/message-active.png"
},
{
"text": "我们",
"pagePath":"pages/contact/contact",
"iconPath":"static/tabs/contact.png",
"selectedIconPath":"static/tabs/contact-active.png"
}
]
}
condition startup mode configuration
The startup mode configuration takes effect only during the development period, and is used to simulate the scenario of direct access to the page, such as: after the applet is forwarded, the user clicks on the opened page.
Property description:
Attributes | type | Is it required? | describe |
---|---|---|---|
current | Number | yes | The currently active mode, the index value of the list node |
list | Array | yes | List of boot modes |
list description:
Attributes | type | Is it required? | describe |
---|---|---|---|
name | String | yes | boot mode name |
path | String | yes | start page path |
query | String | no | Start parameters, which can be obtained in the onLoad function of the page |
Basic use of components
uni-app provides rich basic components for developers. Developers can combine various components to build their own applications like building blocks.
The components in uni-app, just HTML
like the functions of div
the , p
, span
and other tags in , are used to build the infrastructure of the page
Usage of text text component
001 - properties of the text component
Attributes | type | Defaults | required | illustrate |
---|---|---|---|---|
selectable | boolean | false | no | Whether the text is optional |
space | string | . | no | Display continuous spaces, optional parameters: ensp , emsp ,nbsp |
decode | boolean | false | no | 是否解码 |
text
组件相当于行内标签、在同一行显示- 除了文本节点以外的其他节点都无法长按选中
002 - 代码案例
<view>
<!-- 长按文本是否可选 -->
<text selectable='true'>来了老弟</text>
</view>
<view>
<!-- 显示连续空格的方式 -->
<view>
<text space='ensp'>来了 老弟</text>
</view>
<view>
<text space='emsp'>来了 老弟</text>
</view>
<view>
<text space='nbsp'>来了 老弟</text>
</view>
</view>
<view>
<text>skyblue</text>
</view>
<view>
<!-- 是否解码 -->
<text decode='true'> < > & '    </text>
</view>
view视图容器组件的用法
View 视图容器, 类似于 HTML 中的 div
001 - 组件的属性
view
002 - 代码案例
<view class="box2" hover-class="box2_active">
<view class='box1' hover-class='active' hover-stop-propagation :hover-start-time="2000" :hover-stay-time='2000'>
</view>
</view>
button按钮组件的用法
001 - 组件的属性
属性名 | 类型 | 默认值 | 说明 |
---|---|---|---|
size | String | default | 按钮的大小 |
type | String | default | 按钮的样式类型 |
plain | Boolean | false | 按钮是否镂空,背景色透明 |
disabled | Boolean | false | 是否按钮 |
loading | Boolean | false | 名称是否带 loading t图标 |
button
组件默认独占一行,设置size
为mini
时可以在一行显示多个
002 - 案例代码
<button size='mini' type='primary'>前端</button>
<button size='mini' type='default' disabled='true'>前端</button>
<button size='mini' type='warn' loading='true'>前端</button>
image组件的使用
image
图片。
属性名 | 类型 | 默认值 | 说明 | 平台差异说明 |
---|---|---|---|---|
src | String | 图片资源地址 | ||
mode | String | ‘scaleToFill’ | 图片裁剪、缩放的模式 |
Tips
<image>
组件默认宽度 300px、高度 225px;src
仅支持相对路径、绝对路径,支持 base64 码;- 页面结构复杂,css样式太多的情况,使用 image 可能导致样式生效较慢,出现 “闪一下” 的情况,此时设置
image{will-change: transform}
,可优化此问题。
uni-app中的样式
-
rpx 即响应式px,一种根据屏幕宽度自适应的动态单位。以750宽的屏幕为基准,750rpx恰好为屏幕宽度。屏幕变宽,rpx 实际显示效果会等比放大。
-
使用
@import
语句可以导入外联样式表,@import
后跟需要导入的外联样式表的相对路径,用;
表示语句结束 -
支持基本常用的选择器class、id、element等
-
在
uni-app
中不能使用*
选择器。 -
page
相当于body
节点 -
定义在 App.vue 中的样式为全局样式,作用于每一个页面。在 pages 目录下 的 vue 文件中定义的样式为局部样式,只作用在对应的页面,并会覆盖 App.vue 中相同的选择器。
-
uni-app
支持使用字体图标,使用方式与普通web
项目相同,需要注意以下几点:-
字体文件小于 40kb,
uni-app
会自动将其转化为 base64 格式; -
字体文件大于等于 40kb, 需开发者自己转换,否则使用将不生效;
-
字体文件的引用路径推荐使用以 ~@ 开头的绝对路径。
@font-face { font-family: test1-icon; src: url('~@/static/iconfont.ttf'); }
-
-
如何使用scss或者less
uni-app中的数据绑定
在页面中需要定义数据,和我们之前的vue一摸一样,直接在data中定义数据即可
export default {
data () {
return {
msg: 'hello-uni'
}
}
}
插值表达式的使用
-
利用插值表达式渲染基本数据
<view>{ {msg}}</view>
-
在插值表达式中使用三元运算
<view>{ { flag ? '我是真的':'我是假的' }}</view>
-
基本运算
<view>{ {1+1}}</view>
v-bind动态绑定属性
在data中定义了一张图片,我们希望把这张图片渲染到页面上
export default {
data () {
return {
img: 'http://destiny001.gitee.io/image/monkey_02.jpg'
}
}
}
利用v-bind进行渲染
<image v-bind:src="img"></image>
还可以缩写成:
<image :src="img"></image>
v-for的使用
data中定以一个数组,最终将数组渲染到页面上
data () {
return {
arr: [
{
name: '刘能', age: 29 },
{
name: '赵四', age: 39 },
{
name: '宋小宝', age: 49 },
{
name: '小沈阳', age: 59 }
]
}
}
利用v-for进行循环
<view v-for="(item,i) in arr" :key="i">名字:{
{
item.name}}---年龄:{
{
item.age}}</view>
uni中的事件
事件绑定
在uni中事件绑定和vue中是一样的,通过v-on进行事件的绑定,也可以简写为@
<button @click="tapHandle">点我啊</button>
事件函数定义在methods中
methods: {
tapHandle () {
console.log('真的点我了')
}
}
事件传参
-
默认如果没有传递参数,事件函数第一个形参为事件对象
// template <button @click="tapHandle">点我啊</button> // script methods: { tapHandle (e) { console.log(e) } }
-
如果给事件函数传递参数了,则对应的事件函数形参接收的则是传递过来的数据
// template <button @click="tapHandle(1)">点我啊</button> // script methods: { tapHandle (num) { console.log(num) } }
-
如果获取事件对象也想传递参数
// template <button @click="tapHandle(1,$event)">点我啊</button> // script methods: { tapHandle (num,e) { console.log(num,e) } }
uni的生命周期
应用的生命周期
生命周期的概念:一个对象从创建、运行、销毁的整个过程被成为生命周期。
生命周期函数:在生命周期中每个阶段会伴随着每一个函数的触发,这些函数被称为生命周期函数
uni-app
支持如下应用生命周期函数:
函数名 | 说明 |
---|---|
onLaunch | 当uni-app 初始化完成时触发(全局只触发一次) |
onShow | 当 uni-app 启动,或从后台进入前台显示 |
onHide | 当 uni-app 从前台进入后台 |
onError | 当 uni-app 报错时触发 |
页面的生命周期
uni-app
支持如下页面生命周期函数:
函数名 | 说明 | 平台差异说明 | 最低版本 |
---|---|---|---|
onLoad | 监听页面加载,其参数为上个页面传递的数据,参数类型为Object(用于页面传参),参考示例 | ||
onShow | 监听页面显示。页面每次出现在屏幕上都触发,包括从下级页面点返回露出当前页面 | ||
onReady | 监听页面初次渲染完成。 | ||
onHide | 监听页面隐藏 | ||
onUnload | 监听页面卸载 |
下拉刷新
开启下拉刷新
在uni-app中有两种方式开启下拉刷新
- 需要在
pages.json
里,找到的当前页面的pages节点,并在style
选项中开启enablePullDownRefresh
- 通过调用uni.startPullDownRefresh方法来开启下拉刷新
通过配置文件开启
创建list页面进行演示
<template>
<view>
杭州学科
<view v-for="(item,index) in arr" :key="index">
{
{item}}
</view>
</view>
</template>
<script>
export default {
data () {
return {
arr: ['前端','java','ui','大数据']
}
}
}
</script>
<style>
</style>
通过pages.json文件中找到当前页面的pages节点,并在 style
选项中开启 enablePullDownRefresh
{
"path":"pages/list/list",
"style":{
"enablePullDownRefresh": true
}
}
通过API开启
uni.startPullDownRefresh()
监听下拉刷新
通过onPullDownRefresh可以监听到下拉刷新的动作
export default {
data () {
return {
arr: ['前端','java','ui','大数据']
}
},
methods: {
startPull () {
uni.startPullDownRefresh()
}
},
onPullDownRefresh () {
console.log('触发下拉刷新了')
}
}
关闭下拉刷新
uni.stopPullDownRefresh()
停止当前页面下拉刷新。
案例演示
<template>
<view>
<button type="primary" @click="startPull">开启下拉刷新</button>
杭州学科
<view v-for="(item,index) in arr" :key="index">
{
{item}}
</view>
</view>
</template>
<script>
export default {
data () {
return {
arr: ['前端','java','ui','大数据']
}
},
methods: {
startPull () {
uni.startPullDownRefresh()
}
},
onPullDownRefresh () {
this.arr = []
setTimeout(()=> {
this.arr = ['前端','java','ui','大数据']
uni.stopPullDownRefresh()
}, 1000);
}
}
</script>
上拉加载
通过在pages.json文件中找到当前页面的pages节点下style中配置onReachBottomDistance可以设置距离底部开启加载的距离,默认为50px
通过onReachBottom监听到触底的行为
<template>
<view>
<button type="primary" @click="startPull">开启下拉刷新</button>
杭州学科
<view v-for="(item,index) in arr" :key="index">
{
{
item}}
</view>
</view>
</template>
<script>
export default {
data () {
return {
arr: ['前端','java','ui','大数据','前端','java','ui','大数据']
}
},
onReachBottom () {
console.log('触底了')
}
}
</script>
<style>
view{
height: 100px;
line-height: 100px;
}
</style>
网络请求
在uni中可以调用uni.request方法进行请求网络请求
需要注意的是:在小程序中网络相关的 API 在使用前需要配置域名白名单。
发送get请求
<template>
<view>
<button @click="sendGet">发送请求</button>
</view>
</template>
<script>
export default {
methods: {
sendGet () {
uni.request({
url: 'http://localhost:8082/api/getlunbo',
success(res) {
console.log(res)
}
})
}
}
}
</script>
发送post请求
数据缓存
uni.setStorage
将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
代码演示
<template>
<view>
<button type="primary" @click="setStor">存储数据</button>
</view>
</template>
<script>
export default {
methods: {
setStor () {
uni.setStorage({
key: 'id',
data: 100,
success () {
console.log('存储成功')
}
})
}
}
}
</script>
<style>
</style>
uni.setStorageSync
将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
代码演示
<template>
<view>
<button type="primary" @click="setStor">存储数据</button>
</view>
</template>
<script>
export default {
methods: {
setStor () {
uni.setStorageSync('id',100)
}
}
}
</script>
<style>
</style>
uni.getStorage
从本地缓存中异步获取指定 key 对应的内容。
代码演示
<template>
<view>
<button type="primary" @click="getStorage">获取数据</button>
</view>
</template>
<script>
export default {
data () {
return {
id: ''
}
},
methods: {
getStorage () {
uni.getStorage({
key: 'id',
success: res=>{
this.id = res.data
}
})
}
}
}
</script>
uni.getStorageSync
从本地缓存中同步获取指定 key 对应的内容。
代码演示
<template>
<view>
<button type="primary" @click="getStorage">获取数据</button>
</view>
</template>
<script>
export default {
methods: {
getStorage () {
const id = uni.getStorageSync('id')
console.log(id)
}
}
}
</script>
uni.removeStorage
从本地缓存中异步移除指定 key。
代码演示
<template>
<view>
<button type="primary" @click="removeStorage">删除数据</button>
</view>
</template>
<script>
export default {
methods: {
removeStorage () {
uni.removeStorage({
key: 'id',
success: function () {
console.log('删除成功')
}
})
}
}
}
</script>
uni.removeStorageSync
从本地缓存中同步移除指定 key。
代码演示
<template>
<view>
<button type="primary" @click="removeStorage">删除数据</button>
</view>
</template>
<script>
export default {
methods: {
removeStorage () {
uni.removeStorageSync('id')
}
}
}
</script>
上传图片、预览图片
上传图片
uni.chooseImage方法从本地相册选择图片或使用相机拍照。
案例代码
<template>
<view>
<button @click="chooseImg" type="primary">上传图片</button>
<view>
<image v-for="item in imgArr" :src="item" :key="index"></image>
</view>
</view>
</template>
<script>
export default {
data () {
return {
imgArr: []
}
},
methods: {
chooseImg () {
uni.chooseImage({
count: 9,
success: res=>{
this.imgArr = res.tempFilePaths
}
})
}
}
}
</script>
预览图片
结构
<view>
<image v-for="item in imgArr" :src="item" @click="previewImg(item)" :key="item"></image>
</view>
预览图片的方法
previewImg (current) {
uni.previewImage({
urls: this.imgArr,
current
})
}
条件注释实现跨段兼容
条件编译是用特殊的注释作为标记,在编译时根据这些特殊的注释,将注释里面的代码编译到不同平台。
**写法:**以 #ifdef 加平台标识 开头,以 #endif 结尾。
平台标识
值 | 平台 | 参考文档 |
---|---|---|
APP-PLUS | 5+App | HTML5+ 规范 |
H5 | H5 | |
MP-WEIXIN | 微信小程序 | 微信小程序 |
MP-ALIPAY | 支付宝小程序 | 支付宝小程序 |
MP-BAIDU | 百度小程序 | 百度小程序 |
MP-TOUTIAO | 头条小程序 | 头条小程序 |
MP-QQ | QQ小程序 | (目前仅cli版支持) |
MP | 微信小程序/支付宝小程序/百度小程序/头条小程序/QQ小程序 |
组件的条件注释
代码演示
<!-- #ifdef H5 -->
<view>
h5页面会显示
</view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view>
微信小程序会显示
</view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<view>
app会显示
</view>
<!-- #endif -->
api的条件注释
代码演示
onLoad () {
//#ifdef MP-WEIXIN
console.log('微信小程序')
//#endif
//#ifdef H5
console.log('h5页面')
//#endif
}
样式的条件注释
代码演示
/* #ifdef H5 */
view{
height: 100px;
line-height: 100px;
background: red;
}
/* #endif */
/* #ifdef MP-WEIXIN */
view{
height: 100px;
line-height: 100px;
background: green;
}
/* #endif */
uni中的导航跳转
利用navigator进行跳转
navigator详细文档:文档地址
跳转到普通页面
<navigator url="/pages/about/about" hover-class="navigator-hover">
<button type="default">跳转到关于页面</button>
</navigator>
跳转到tabbar页面
<navigator url="/pages/message/message" open-type="switchTab">
<button type="default">跳转到message页面</button>
</navigator>
利用编程式导航进行跳转
导航跳转文档
利用navigateTo进行导航跳转
保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack
可以返回到原页面。
<button type="primary" @click="goAbout">跳转到关于页面</button>
通过navigateTo方法进行跳转到普通页面
goAbout () {
uni.navigateTo({
url: '/pages/about/about',
})
}
通过switchTab跳转到tabbar页面
跳转到tabbar页面
<button type="primary" @click="goMessage">跳转到message页面</button>
通过switchTab方法进行跳转
goMessage () {
uni.switchTab({
url: '/pages/message/message'
})
}
redirectTo进行跳转
关闭当前页面,跳转到应用内的某个页面。
<!-- template -->
<button type="primary" @click="goMessage">跳转到message页面</button>
<!-- js -->
goMessage () {
uni.switchTab({
url: '/pages/message/message'
})
}
通过onUnload测试当前组件确实卸载
onUnload () {
console.log('组件卸载了')
}
导航跳转传递参数
在导航进行跳转到下一个页面的同时,可以给下一个页面传递相应的参数,接收参数的页面可以通过onLoad生命周期进行接收
传递参数的页面
goAbout () {
uni.navigateTo({
url: '/pages/about/about?id=80',
});
}
接收参数的页面
<script>
export default {
onLoad (options) {
console.log(options)
}
}
</script>
uni-app中组件的创建
在uni-app中,可以通过创建一个后缀名为vue的文件,即创建一个组件成功,其他组件可以将该组件通过impot的方式导入,在通过components进行注册即可
-
创建login组件,在component中创建login目录,然后新建login.vue文件
<template> <view> 这是一个自定义组件 </view> </template> <script> </script> <style> </style>
-
在其他组件中导入该组件并注册
import login from "@/components/test/test.vue"
-
注册组件
components: { test}
-
使用组件
<test></test>
组件的生命周期函数
beforeCreate | 在实例初始化之后被调用。详见 | ||
---|---|---|---|
created | 在实例创建完成后被立即调用。详见 | ||
beforeMount | 在挂载开始之前被调用。详见 | ||
mounted | 挂载到实例上去之后调用。详见 注意:此处并不能确定子组件被全部挂载,如果需要子组件完全挂载之后在执行操作可以使用$nextTick Vue官方文档 |
||
beforeUpdate | 数据更新时调用,发生在虚拟 DOM 打补丁之前。详见 | 仅H5平台支持 | |
updated | 由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。详见 | 仅H5平台支持 | |
beforeDestroy | 实例销毁之前调用。在这一步,实例仍然完全可用。详见 | ||
destroyed | Vue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。详见 |
组件的通讯
父组件给子组件传值
通过props来接受外界传递到组件内部的值
<template>
<view>
这是一个自定义组件 {
{
msg}}
</view>
</template>
<script>
export default {
props: ['msg']
}
</script>
<style>
</style>
其他组件在使用login组件的时候传递值
<template>
<view>
<test :msg="msg"></test>
</view>
</template>
<script>
import test from "@/components/test/test.vue"
export default {
data () {
return {
msg: 'hello'
}
},
components: {
test}
}
</script>
子组件给父组件传值
通过$emit触发事件进行传递参数
<template>
<view>
这是一个自定义组件 {
{msg}}
<button type="primary" @click="sendMsg">给父组件传值</button>
</view>
</template>
<script>
export default {
data () {
return {
status: '打篮球'
}
},
props: {
msg: {
type: String,
value: ''
}
},
methods: {
sendMsg () {
this.$emit('myEvent',this.status)
}
}
}
</script>
父组件定义自定义事件并接收参数
<template>
<view>
<test :msg="msg" @myEvent="getMsg"></test>
</view>
</template>
<script>
import test from "@/components/test/test.vue"
export default {
data () {
return {
msg: 'hello'
}
},
methods: {
getMsg (res) {
console.log(res)
}
},
components: {
test}
}
</script>
兄弟组件通讯
uni-ui的使用
1、进入Grid宫格组件
2、使用HBuilderX导入该组件
3、导入该组件
import uniGrid from "@/components/uni-grid/uni-grid.vue"
import uniGridItem from "@/components/uni-grid-item/uni-grid-item.vue"
4、注册组件
components: {
uniGrid,uniGridItem}
5、使用组件
<uni-grid :column="3">
<uni-grid-item>
<text class="text">文本</text>
</uni-grid-item>
<uni-grid-item>
<text class="text">文本</text>
</uni-grid-item>
<uni-grid-item>
<text class="text">文本</text>
</uni-grid-item>
</uni-grid>