欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

【uni-app】uni-app的基础知识

发布时间:2023/12/8 53 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【uni-app】uni-app的基础知识 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

uni-app的基本使用

课程介绍:

基础部分:

  • 环境搭建
  • 页面外观配置
  • 数据绑定
  • uni-app的生命周期
  • 组件的使用
  • uni-app中样式学习
  • 在uni-app中使用字体图标和开启scss
  • 条件注释跨端兼容
  • uni中的事件
  • 导航跳转
  • 组件创建和通讯,及组件的生命周期
  • uni-app中使用uni-ui库

项目:黑马商城项目

1.uni-app介绍 官方网页

uni-app 是一个使用 Vue.js 开发所有前端应用的框架,开发者编写一套代码,可发布到iOS、Android、H5、以及各种小程序(微信/支付宝/百度/头条/QQ/钉钉)等多个平台。

即使不跨端,uni-app同时也是更好的小程序开发框架。

具有vue和微信小程序的开发经验,可快速上手uni-app

为什么要去学习uni-app?

相对开发者来说,减少了学习成本,因为只学会uni-app之后,即可开发出iOS、Android、H5、以及各种小程序的应用,不需要再去学习开发其他应用的框架,相对公司而言,也大大减少了开发成本。

1.1环境搭建

安装编辑器HbuilderX 下载地址

HBuilderX是通用的前端开发工具,但为uni-app做了特别强化。

下载App开发版,可开箱即用

安装微信开发者工具 下载地址

1.2利用HbuilderX初始化项目

  • 点击HbuilderX菜单栏文件>项目>新建

  • 选择uni-app,填写项目名称,项目创建的目录

1.3运行项目

在菜单栏中点击运行,运行到浏览器,选择浏览器即可运行

项目运行-浏览器:

项目运行-微信开发者工具

注意事项:
(1)使用微信开发者工具运行项目时,需要添加微信开发者工具的目录
(2)在微信开发者工具-设置-安全设置:打开端口

注意:

  • 如果是第一次使用,需要先配置小程序ide的相关路径,才能运行成功
  • 微信开发者工具在设置中安全设置,服务端口开启

1.4 介绍项目目录和文件作用

  • pages.json 文件用来对 uni-app 进行全局配置,决定页面文件的路径、窗口样式、原生的导航栏、底部的原生tabbar 等

  • manifest.json 文件是应用的配置文件,用于指定应用的名称、图标、权限等。

  • App.vue是我们的跟组件,所有页面都是在App.vue下进行切换的,是页面入口文件,可以调用应用的生命周期函数。

  • main.js是我们的项目入口文件,主要作用是初始化vue实例并使用需要的插件。

  • uni.scss文件的用途是为了方便整体控制应用的风格。比如按钮颜色、边框风格,uni.scss文件里预置了一批scss变量预置。

  • unpackage就是打包目录,在这里有各个平台的打包文件

  • pages所有的页面存放目录

  • static静态资源目录,例如图片等

  • components组件存放目录


为了实现多端兼容,综合考虑编译速度、运行性能等因素,uni-app 约定了如下开发规范:

  • 页面文件遵循 Vue 单文件组件 (SFC) 规范
  • 组件标签靠近小程序规范,详见uni-app 组件规范
  • 接口能力(JS API)靠近微信小程序规范,但需将前缀 wx 替换为 uni,详见uni-app接口规范
  • 数据绑定及事件处理同 Vue.js 规范,同时补充了App及页面的生命周期
  • 为兼容多端运行,建议使用flex布局进行开发

2.全局配置和页面配置

2.1通过globalStyle进行全局配置

用于设置应用的状态栏、导航条、标题、窗口背景色等。详细文档

属性类型默认值描述
navigationBarBackgroundColorHexColor#F7F7F7导航栏背景颜色(同状态栏背景色)
navigationBarTextStyleStringwhite导航栏标题颜色及状态栏前景颜色,仅支持 black/white
navigationBarTitleTextString导航栏标题文字内容
backgroundColorHexColor#ffffff窗口的背景色
backgroundTextStyleStringdark下拉 loading 的样式,仅支持 dark / light
enablePullDownRefreshBooleanfalse是否开启下拉刷新,详见页面生命周期。
onReachBottomDistanceNumber50页面上拉触底事件触发时距页面底部距离,单位只支持px,详见页面生命周期

2.2创建新的message页面

右键pages新建message目录,在message目录下右键新建.vue文件,并选择基本模板

<template><view>这是信息页面</view> </template><script> </script><style> </style>

2.3通过pages来配置页面

属性类型默认值描述
pathString配置页面路径
styleObject配置页面窗口表现,配置项参考 pageStyle

pages数组数组中第一项表示应用启动页

"pages": [ 、{"path":"pages/message/message"},{"path": "pages/index/index","style": {"navigationBarTitleText": "uni-app"}}]

通过style修改页面的标题和导航栏背景色,并且设置h5下拉刷新的特有样式

"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"}}}}]

2.4 配置tabbar

如果应用是一个多 tab 应用,可以通过 tabBar 配置项指定 tab 栏的表现,以及 tab 切换时显示的对应页。

Tips

  • 当设置 position 为 top 时,将不会显示 icon,只会显示文字
  • tabBar 中的 list 是一个数组,只能配置最少2个、最多5个 tab,tab 按数组的顺序排序。

属性说明:

属性类型必填默认值描述平台差异说明
colorHexColortab 上的文字默认颜色
selectedColorHexColortab 上的文字选中时的颜色
backgroundColorHexColortab 的背景色
borderStyleStringblacktabbar 上边框的颜色,仅支持 black/whiteApp 2.3.4+ 支持其他颜色值
listArraytab 的列表,详见 list 属性说明,最少2个、最多5个 tab
positionStringbottom可选值 bottom、toptop 值仅微信小程序支持

其中 list 接收一个数组,数组中的每个项都是一个对象,其属性值如下:

属性类型必填说明
pagePathString页面路径,必须在 pages 中先定义
textStringtab 上按钮文字,在 5+APP 和 H5 平台为非必填。例如中间可放一个没有文字的+号图标
iconPathString图片路径,icon 大小限制为40kb,建议尺寸为 81px * 81px,当 postion 为 top 时,此参数无效,不支持网络图片,不支持字体图标
selectedIconPathString选中时的图片路径,icon 大小限制为40kb,建议尺寸为 81px * 81px ,当 postion 为 top 时,此参数无效

案例代码:

{"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages{"path": "pages/message/message","style": {"navigationBarTitleText": "信息页","navigationBarBackgroundColor": "red","h5":{"pullToRefresh":{"color":"blue"}}}},{"path": "pages/index/index","style": {"navigationBarTitleText": "my-first project"}},{"path": "pages/contact/contact","style": {"navigationBarTitleText": "信息页","navigationBarBackgroundColor": "red","h5":{"pullToRefresh":{"color":"blue"}}}}],"globalStyle": {//导航栏标题颜色及状态栏前景颜色,仅支持black/white"navigationBarTextStyle": "white","navigationBarTitleText": "my-first project",//导航栏背景颜色(同状态栏背景色)"navigationBarBackgroundColor": "pink","backgroundColor": "#F8F8F8",//开启下拉刷新"enablePullDownRefresh":true},"tabBar":{"color":"#F0AD4E","selectedColor":"#4CD964","backgroundColor":"#DD524D","borderStyle":"F8F8F8","list":[{"text":"首页","pagePath":"pages/index/index","iconPath":"static/tab/home.png","selectedIconPath":"static/tab/home-active.png"},{"text":"信息","pagePath":"pages/message/message","iconPath":"static/tab/message.png","selectedIconPath":"static/tab/message-active.png"},{"text":"联系我们","pagePath":"pages/contact/contact","iconPath":"static/tab/contact.png","selectedIconPath":"static/tab/contact-active.png"}]} }

2.5 condition启动模式配置

启动模式配置,仅开发期间生效,用于模拟直达页面的场景,如:小程序转发后,用户点击所打开的页面。

属性说明:

属性类型是否必填描述
currentNumber当前激活的模式,list节点的索引值
listArray启动模式列表

list说明:

属性类型是否必填描述
nameString启动模式名称
pathString启动页面路径
queryString启动参数,可在页面的 onLoad 函数里获得
//启动模式配置,仅开发期间有效,用于模拟直达页面的场景。"condition":{"current":0,//当前激活的模式"list":{"name":"详情页",//模式名称"path":"pages/detail/detail.vue",//启动页面"query":"interval=4000&autoplay=false"//启动参数,前一个页面传递过来的参数}}

3.组件的基本使用

uni-app提供了丰富的基础组件给开发者,开发者可以像搭积木一样,组合各种组件拼接称自己的应用

uni-app中的组件,就像 HTML 中的 div 、p、span 等标签的作用一样,用于搭建页面的基础结构

3.1 text文本组件的用法(类似于span标签)

001 - text 组件的属性

属性类型默认值必填说明
selectablebooleanfalse文本是否可选
spacestring.显示连续空格,可选参数:ensp、emsp、nbsp
decodebooleanfalse是否解码
  • text 组件相当于行内标签、在同一行显示
  • 除了文本节点以外的其他节点都无法长按选中
text的属性:(1)selectable:文本是否可选(2)space:显示连续空格ensp:中文字符空格一半大小emsp:中文字符空格大小nbsp:根据字体设置的空格大小(3)decode:是否解码,目前都已经自动解码了。可以解析的有 &nbsp; &lt; &gt; &amp; &apos; &ensp;

002 - 代码案例

<template><view><view>信息</view><!-- text的属性:(1)selectable:文本是否可选(2)space:显示连续空格ensp:中文字符空格一半大小emsp:中文字符空格大小nbsp:根据字体设置的空格大小(3)decode:是否解码,目前都已经自动解码了。可以解析的有 &nbsp; &lt; &gt; &amp; &apos; &ensp; --><view> <!-- 等于span标签,默认是不可以选中的--> <text>跳舞唱歌化妆</text> </view><view><!-- selectable文本是否可选,默认是不可以选的。 --><text selectable>跳舞唱歌化妆</text></view><!-- space显示连续的空格ensp:中文字符空格一半大小emsp:中文字符空格大小nbsp:根据字体设置的空格大小 --><view><text space="ensp">跳舞 唱歌化妆</text></view><view><text space="emsp">跳舞 唱歌化妆</text></view><view><text space="nbsp">跳舞 唱歌化妆</text></view><view><text space="nbsp" decode>跳舞 唱歌化妆&amp;</text></view></view></template><script> </script><style> </style>

3.2 view视图容器组件的用法(类似于div标签)—template中必须有一个根组件

View 视图容器, 类似于 HTML 中的 div

001 - 组件的属性

002 - 代码案例

<!-- view的属性:hover-class:按下去时的样式类hover-stop-propagation:阻止冒泡(在孩子处阻止冒泡)hover-start-time:按住后多久出现点击态,单位毫秒hover-stay-time:手指松开后保留态的时间,单位毫秒 --><view class="box2" hover-class="box2-active"><view class="box1" hover-class="box1-active" hover-stop-propagation hover-start-time="2000" hover-stay-time="2000">我是一个大盒子</view></view>

3.3 button按钮组件的用法

001 - 组件的属性

属性名类型默认值说明
sizeStringdefault按钮的大小
typeStringdefault按钮的样式类型
plainBooleanfalse按钮是否镂空,背景色透明
disabledBooleanfalse是否按钮
loadingBooleanfalse名称是否带 loading t图标
  • button 组件默认独占一行,设置 size 为 mini 时可以在一行显示多个

002 - 案例代码

<!-- button的属性:size:设置大小type:按钮样式plain:镂空disabled:禁止点击loading:加载样式 --><view><button>点击</button><button size="default">点击</button><button size="mini">点击</button><button type="default">点击</button><button type="primary">点击</button><button type="warn">点击</button><button type="primary" plain>点击</button><button type="primary" disabled="false">点击</button><button type="primary" loading>点击</button></view>

3.4 image组件的使用

image

image的属性:<view><image src="../../static/logo.png"></image><image src="../../static/logo.png" mode="aspectFit"></image><image src="../../static/logo.png" mode="aspectFill"></image> </view>

Tips

  • <image> 组件默认宽度 300px、高度 225px;
  • src 仅支持相对路径、绝对路径,支持 base64 码;
  • 页面结构复杂,css样式太多的情况,使用 image 可能导致样式生效较慢,出现 “闪一下” 的情况,此时设置 image{will-change: transform} ,可优化此问题。

4.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

5.uni-app中的数据绑定

在页面中需要定义数据,和我们之前的vue一摸一样,直接在data中定义数据即可

export default {data () {return {msg: 'hello-uni'}} }

5.1插值表达式的使用

  • 利用插值表达式渲染基本数据

    <view>{{msg}}</view>
  • 在插值表达式中使用三元运算

    <view>{{ flag ? '我是真的':'我是假的' }}</view>
  • 基本运算

    <view>{{1+1}}</view>

代码:

<template><view><view>数据绑定的学习</view><view>{{msg}}</view><view>{{'你好'+'世界'}}</view><view>{{1+1}}</view><view>{{flag?'我是真的':'我是假的'}}</view></view> </template><script>export default{data(){return {msg:'hello world',flag:false}}} </script><style> </style>

5.2v-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>

5.3v-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>

5.4 代码

<template><view><view>数据绑定的学习</view><view>{{msg}}</view><view>{{'你好'+'世界'}}</view><view>{{1+1}}</view><view>{{flag?'我是真的':'我是假的'}}</view><view><image :src="imgUrl"></image><image v-bind:src="imgUrl"></image></view><view v-for="(item,index) in list">序号:{{index}},名字:{{item.name}},年龄:{{item.age}}</view></view> </template><script>export default{data(){return {msg:'hello world',flag:false,imgUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp05%2F191001214Q53137-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651155579&t=0b7de5e11caa724eaa217169648d7a4b",list:[{'name':'李四','age':'23'},{'name':'李四','age':'23'},{'name':'李四','age':'23'}]}}} </script><style> </style>

6. uni中的事件

6.1事件绑定

在uni中事件绑定和vue中是一样的,通过v-on进行事件的绑定,也可以简写为@

<button @click="tapHandle">点我啊</button>

事件函数定义在methods中

methods: {tapHandle () {console.log('真的点我了')} }

6.2 事件传参

  • 默认如果没有传递参数,事件函数第一个形参为事件对象

    // template <button @click="tapHandle">点我啊</button> // script methods: {tapHandle (e) {console.log(e)} } // template <button @click="tapHandle($event)">点我啊</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)} }

7.uni的生命周期

7.1应用的生命周期(只能在App.vue里监听应用的生命周期)

生命周期的概念:一个对象从创建、运行、销毁的整个过程被成为生命周期。

生命周期函数:在生命周期中每个阶段会伴随着每一个函数的触发,这些函数被称为生命周期函数

uni-app 支持如下应用生命周期函数:

函数名说明
onLaunch当uni-app 初始化完成时触发(全局只触发一次)
onShow当 uni-app 启动,或从后台进入前台显示,通俗的说就是打开应用时,就会显示
onHide当 uni-app 从前台进入后台,就是将该应用置于后台
onError当 uni-app 报错时触发

App.vue的代码

<script>// 应用的生命周期:[只能写在App.vue中]// onLaunch:初始化完成时触发,全局只触发一次// onShow:启动时,或者从后台进入前台显示.通俗的说就是打开应用时,就会显示// onHide:从前台进入后台,就是将该应用置于后台// onError:报错时触发export default{onLaunch:function(){console.log("应用的生命周期:初始化时完成触发,全局只触发一次")},onShow:function(){console.log("应用的生命周期,启动时或者从后台进入前台显示,通俗的说就是打开应用时,就会显示")},onHide:function(){console.log("应用的生命周期:从前台进入后台,就是将该应用置于后台")},onError:function(){console.log("报错了。")}} </script><style>/*每个页面公共css */ </style>

7.2页面的生命周期(写在需要监听的页面上)

uni-app 支持如下页面生命周期函数:

函数名说明平台差异说明最低版本
onLoad(不会多次触发监听页面加载,其参数为上个页面传递的数据,参数类型为Object(用于页面传参),参考示例
onShow监听页面显示。页面每次出现在屏幕上都触发,包括从下级页面点返回露出当前页面
onReady(不会触发多次)监听页面初次渲染完成。
onHide监听页面隐藏
onUnload监听页面卸载

监听index.vue为例:
index.vue的代码:

<template><view class="content"><image class="logo" src="/static/logo.png"></image><view class="text-area"><text class="title">{{title}}</text></view></view> </template><script>export default {data() {return {title: 'Hello'}},onLoad() {console.log("onLoad,监听页面加载,不会多次")},onShow(){console.log("onShow,监听页面显示,页面每次出现在屏幕上时都触发")},onReady(){console.log("onReady,监听页面初次渲染完成。")},onHide(){console.log("监听页面隐藏")},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>

7.3 组件的生命周期(与vue组件的一样)

组件的生命周期

8.下拉刷新

8.1 开启下拉刷新

在uni-app中有两种方式开启下拉刷新

  • 需要在 pages.json 里,找到的当前页面的pages节点,并在 style 选项中开启 enablePullDownRefresh【不建议全局开启刷新】
  • 通过调用uni.startPullDownRefresh方法来开启下拉刷新

8.1.1 方法1:通过配置文件开启【不建议全局设置刷新】

创建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} }

8.1.2 方法2: 通过API开启

api文档

uni.startPullDownRefresh()

8.2 监听下拉刷新(与onLoad同级)

通过onPullDownRefresh可以监听到下拉刷新的动作

export default {data () {return {arr: ['前端','java','ui','大数据']}},methods: {startPull () {uni.startPullDownRefresh()}},onPullDownRefresh () {console.log('触发下拉刷新了')} }

8.3 关闭下拉刷新

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>

8.4完整代码:

方法1:配置文件设置刷新

使用配置文件里的enablePullDownRefresh:true开启刷新,使用onPullDownRefresh()进行刷新监听,在监听里面进行调用uni.stopPullDownRefresh()关闭刷新。
pages.json

{"pages": {"path": "pages/list/list","style": {"navigationBarTitleText": "my-first project",//开启下拉刷新"enablePullDownRefresh":true}} }

list.vue

<template><view><view v-for="item in arr">{{item}}</view></view> </template><script>export default{data(){return {arr:['前端','java','ui','大数据']}},onPullDownRefresh(){setTimeout(()=>{console.log("下拉刷新了")this.arr=['前端','ui','java','大数据']uni.stopPullDownRefresh()},2000)}} </script><style> </style>

方法2:手动调用api开启刷新

点击按钮进行手动调用uni.startPullDownRefresh(),开启刷新。使用onPullDownRefresh监听下拉加载事件,在监听下拉加载事件里添加关闭加载的事件uni.stopPullDownRefresh()
代码:

<template><view><view v-for="item in arr">{{item}}</view><button type="primary" @click="pullRefresh">点击</button></view> </template><script>export default{data(){return {arr:['前端','java','ui','大数据']}},onPullDownRefresh(){setTimeout(()=>{console.log("下拉刷新了")this.arr=['前端','ui','java','大数据']uni.stopPullDownRefresh()},2000)},methods:{pullRefresh(){console.log("开启手动刷新")uni.startPullDownRefresh()}}} </script><style> </style>

9. 上拉加载

通过在pages.json文件中找到当前页面的pages节点下style中配置onReachBottomDistance可以设置距离底部开启加载的距离,默认为50px

通过onReachBottom监听到触底的行为

<template><view><view v-for="item in arr">{{item}}</view><button type="primary" @click="pullRefresh">点击</button></view> </template><script>export default{data(){return {arr:['前端','java','ui','大数据']}},onPullDownRefresh(){setTimeout(()=>{console.log("下拉刷新了")this.arr=['前端','ui','java','大数据']uni.stopPullDownRefresh()},2000)},onReachBottom(){console.log("页面上拉触底了~")},methods:{pullRefresh(){console.log("开启手动刷新")uni.startPullDownRefresh()}}} </script><style>view{height: 600px;line-height: 100px;} </style> "pages": [ {"path": "pages/list/list","style": {"navigationBarTitleText": "my-first project",//开启下拉刷新"enablePullDownRefresh":true,"onReachBottomDistance":950}},

10. 网络请求

在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请求

11. 数据缓存

11.1 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>

11.2 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>

11.3 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>

11.4 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>

11.5 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>

11.6 uni.removeStorageSync

从本地缓存中同步移除指定 key。

代码演示

<template><view><button type="primary" @click="removeStorage">删除数据</button></view> </template> <script>export default {methods: {removeStorage () {uni.removeStorageSync('id')}}} </script>

12. 上传图片、预览图片

12.1上传图片

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,//必须要写成箭头函数,要不然this就是window,无法获取外面的数据success: res=>{this.imgArr = res.tempFilePaths}})}}} </script>

12.2 预览图片

结构

<view><image v-for="item in imgArr" :src="item" @click="previewImg(item)" :key="item"></image> </view>

预览图片的方法

previewImg (current) {uni.previewImage({urls: this.imgArr,current}) }

12.3 完整代码

<template><view><view>详情页</view><view><button type="primary" @click="chooseImage">上传图片</button></view><view v-for="item in imgArr"><image :src="item" mode="" @click="previewImage(item)"></image></view></view></template><script>export default{data(){return{imgArr:[],}},methods:{chooseImage(){uni.chooseImage({count:5,success:res=>{console.log(res.tempFilePaths)this.imgArr=res.tempFilePaths},fail(res){console.log(res)}})},previewImage(current){uni.previewImage({current:current,urls:this.imgArr,longPressActions:{itemList:['收藏','保存','分享'],success(res){console.log("用户选中了第",+(res.tapIndex+1)+"个按钮,第"+(res.index+1)+"个图片")}},success(){console.log("预览成功")},fail(){console.log("预览失败")}})}}} </script><style> </style>

13. 条件注释实现跨段兼容

条件编译是用特殊的注释作为标记,在编译时根据这些特殊的注释,将注释里面的代码编译到不同平台。

**写法:**以 #ifdef 加平台标识 开头,以 #endif 结尾。

平台标识

值平台参考文档
APP-PLUS5+AppHTML5+ 规范
H5H5
MP-WEIXIN微信小程序微信小程序
MP-ALIPAY支付宝小程序支付宝小程序
MP-BAIDU百度小程序百度小程序
MP-TOUTIAO头条小程序头条小程序
MP-QQQQ小程序(目前仅cli版支持)
MP微信小程序/支付宝小程序/百度小程序/头条小程序/QQ小程序

13.1组件的条件注释

代码演示

<!-- #ifdef H5 --> <view>h5页面会显示 </view> <!-- #endif --> <!-- #ifdef MP-WEIXIN --> <view>微信小程序会显示 </view> <!-- #endif --> <!-- #ifdef APP-PLUS --> <view>app会显示 </view> <!-- #endif -->

13.2api的条件注释

代码演示

onLoad () {//#ifdef MP-WEIXINconsole.log('微信小程序')//#endif//#ifdef H5console.log('h5页面')//#endif }

13.3样式的条件注释

代码演示

/* #ifdef H5 */ view{height: 100px;line-height: 100px;background: red; } /* #endif */ /* #ifdef MP-WEIXIN */ view{height: 100px;line-height: 100px;background: green; } /* #endif */

14. uni中的导航跳转

14.1利用navigator进行跳转

navigator详细文档:文档地址

(1)open-type="navigate" 跳转到普通页面(默认跳转到单页面上,保留当前页面,打开新的页面后,还可以返回到上一级页面)

<navigator url="/pages/about/about" hover-class="navigator-hover"><button type="default">跳转到关于页面</button> </navigator>

(2)open-type="switchTab" 跳转到tabbar页面(如果不加open-type=“switchTab”,就跳转不过来,卸载非tabbar页面,打开新的页面)卸载所有非tabbar页面

<navigator url="/pages/message/message" open-type="switchTab"><button type="default">跳转到message页面</button> </navigator>

(3)open-type="redirect" 跳转到单个页面(卸载当前页面,打开新的页面,不可以返回到上一级页面)卸载当前页面

<navigator url="/pages/message/message" open-type="redirect"><button type="default">跳转到message页面</button> </navigator>

14.2利用编程式导航进行跳转

导航跳转文档

(1)利用navigateTo进行导航跳转

保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面。

<button type="primary" @click="goAbout">跳转到关于页面</button>

通过navigateTo方法进行跳转到普通页面

goAbout () {uni.navigateTo({url: '/pages/about/about',}) }

(2)通过switchTab跳转到tabbar页面

跳转到tabbar页面

<button type="primary" @click="goMessage">跳转到message页面</button>

通过switchTab方法进行跳转

goMessage () {uni.switchTab({url: '/pages/message/message'}) }

(3)redirectTo进行跳转

关闭当前页面,跳转到应用内的某个页面。

<!-- template --> <button type="primary" @click="goMessage">跳转到message页面</button> <!-- js --> goMessage () {uni.redirectTo({url: '/pages/message/message'}) }

通过onUnload测试当前组件确实卸载

onUnload () {console.log('组件卸载了') }

14.3导航跳转传递参数

在导航进行跳转到下一个页面的同时,可以给下一个页面传递相应的参数,接收参数的页面可以通过onLoad生命周期进行接收

传递参数的页面

goAbout () {uni.navigateTo({url: '/pages/about/about?id=80&name='小王'',}); }

接收参数的页面

<script>export default {onLoad (options) {console.log(options)}} </script>

14.4 完整代码

navigator.vue

<template><view><view>导航栏跳转的学习</view><!-- 方法1:使用navigator组件。url:跳转的地址open-type:跳转的方式:默认是跳转单页面,不跳转tab导航页,如果要的话,改成switchTab。不卸载当前页面,打开新的页面,可以返回之前的页面。navigate:默认跳转单页面(即没有tab导航页)redirect:卸载当前页面,打开新的页面,意思就是无法返回到之前的页面。 --><navigator url="../datail/detail?id=20&name='小王'">跳转详情页</navigator><navigator url="../message/message" open-type="switchTab">跳转信息页</navigator><navigator url="../datail/detail" open-type="redirect">跳转详情页(卸载之前的页面)</navigator><!-- 方法2:使用api跳转的方式 --><button type="primary" @click="goDetail">跳转到详情页(保留当前页面,跳转到应用的某个页面,tarbar跳转不过去)</button><button type="primary" @click="goMessage">跳转到信息页</button><button type="primary" @click="redirectDetail">跳转到详情页(卸载当前页面,跳转到新的页面)</button></view> </template><script>export default{data(){return{}},methods:{goDetail(){//保留当前页面,跳转到应用的某个页面(tarbar跳转不过去)uni.navigateTo({url:"../datail/detail"})},goMessage(){//卸载所有非tabbar的页面,打开新的页面uni.switchTab({url:"../message/message"})},redirectDetail(){//卸载当前页面,打开新的页面。uni.redirectTo({url:"../datail/detail"})}},onUnload(){console.log("当前页面卸载了")}} </script><style> </style>

detail.vue

onLoad(options){// #ifdef H5console.log("h5页面会显示")console.log(options)// #endif// #ifdef MP-WEIXINconsole.log("微信小程序会显示")// #endif},

15. 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>

15.1 组件的生命周期函数

beforeCreate在实例初始化之后被调用。详见
created在实例创建完成后被立即调用。详见用于初始化数据
beforeMount在挂载开始之前被调用。详见
mounted挂载到实例上去之后调用。详见 注意:此处并不能确定子组件被全部挂载,如果需要子组件完全挂载之后在执行操作可以使用$nextTickVue官方文档用于操作dom
beforeUpdate数据更新时调用,发生在虚拟 DOM 打补丁之前。详见仅H5平台支持
updated由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。详见仅H5平台支持
beforeDestroy实例销毁之前调用。在这一步,实例仍然完全可用。详见
destroyedVue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。详见可以销毁的时候删除定时器

15.2 代码

uniapp的页面index.vue

<template><view class="content"><!-- <image class="logo" src="/static/logo.png"></image><view class="text-area"><text class="title">{{title}}</text></view> --><test v-if="flag"></test><button @click="changeFlag">切换</button></view> </template><script>import test from '../components/test.vue'export default {data() {return {title: 'Hello',flag:true}},components:{test},methods: {changeFlag(){this.flag=!this.flag}}} </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>

组件test.vue

<template><view>test</view></template><script>export default{data(){return {title:'hello',interId:'null',}},beforeCreate() {//开始初始化,但是还未加载监听拦截,data中的数据还不能加载出来。console.log("beforeCreate:")console.log("data中的数据还不能加载出来:",this.title)},//初始化完成,监听拦截加载完成,data中的数据可以加载出来created(){console.log("created:")console.log("data中的数据可以加载出来了",this.title)this.interId=setInterval(()=>{console.log("执行定时器中....")},1000)},//dom还没有挂载到树上beforeMount(){console.log("beforeMount:")console.log(document.getElementById("name"))},//dom已经挂载到树上了mounted(){console.log("mounted:")console.log(document.getElementById("name"))},//销毁,可以关闭定时器destroyed(){console.log("组件销毁了...")clearInterval(this.interId)},} </script><style> </style>

16. 组件的通讯

16.1父组件给子组件传值

子组件:通过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>

16.2子组件给父组件传值

子组件:通过$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>

父组件:父组件定义自定义事件并接收参数【getMsg函数不能加()】

<template><view><test :msg="msg" @myEvent="getMsg"></test>这是子组件传递给父组件的值{{num}}</view> </template> <script>import test from "@/components/test/test.vue"export default {data () {return {msg: 'hello',num:0,}},methods: {getMsg (res) {this.num=resconsole.log(res)}},components: {test}} </script>

16.3兄弟组件通讯(先注册事件,再触发事件)

16.3.1全局事件与局部事件的区别

全局事件:uni.$emit();

局部事件:this.$emit()

在b组件里注册全局事件,a组件点击按钮后就触发该全局事件
a组件

<template><view>这是a组件,要修改b组件的值:<button @click="changeNumB">切换b组件的值</button></view> </template><script>export default{data(){return{}},methods:{changeNumB(){uni.$emit('changeNum',10)}}} </script><style> </style>

b组件

<template><view>这是b组件,b组件的值:{{num}}</view> </template><script>export default{data(){return {num:20}},created(){//注册全局事件uni.$on('changeNum',(a)=>{this.num+=a})}} </script><style> </style>

首页

<template><view class="content"><test-a></test-a><test-b></test-b></view> </template><script>import testA from '../components/a.vue'import testB from '../components/b.vue'export default {components:{'test-a':testA,'test-b':testB,},} </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>

17. uni-ui的使用

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>

总结

以上是生活随笔为你收集整理的【uni-app】uni-app的基础知识的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。