uni-app基本使用
uni-app的菜鸟级入门教学
文章目录
uni-app项目结构

git管理
首先书写.gitignore文件,并添加/node_modules和 /unpackage/dist
由于/node_modules是进行一些第三方的模块下载,不用进行git管理
/unpackage/dist是运行时候产生的文件,不用进行git管理
管理步骤
-
进行管理之前,一定要加入仓库中
-
首先初始化git仓库,在项目功能下,按住shift+鼠标右键,打开powershell
-
使用
git init初始化git仓库 -
配置用户信息
git config --global user.email "your@email.com" git config --global user.name "Your Name" -
添加远程仓库
git remote add origin https://github.com/username/reponame.git -
使用
git all .提交文件给git跟踪 -
使用
git commit -m "init project"本地提交,-m是加上提示信息,必须加 -
使用
git status查看当前状态 -
使用
git push -u origin master上传本地仓库内容 -
使用
git checkout -b 分支名创建一个分支 -
使用
git branch查看分支
分支的创建,提交与合并
- 使用
git checkout -b 分支名创建一个分支 - 使用
git branch查看分支 - 将创分支提交到本地
git add .git commit -m "提示信息"


项目基础搭建
-
在pages目录下创建对应页面
-
在pages.json下配置tabBar,这样就创建好了对应页面的底部导航栏
-
"tabBar": { "selectedColor": "#0000ff", //这里是设置选中颜色 "list": [{ "pagePath": "pages/home/home", "text": "首页", "iconPath": "/static/index.png", "selectedIconPath": "/static/index-fill.png" }, { "pagePath": "pages/cart/cart", "text": "购物车", "iconPath": "/static/love.png", "selectedIconPath": "/static/love (1).png" }, { "pagePath": "pages/cate/cate", "text": "文创", "iconPath": "/static/wenchuang.png", "selectedIconPath": "/static/wenchuangxuanzhong.png" }, { "pagePath": "pages/my/my", "text": "我的", "iconPath": "/static/mine.png", "selectedIconPath": "/static/mine (1).png" } ] }, -
设置每个页面顶部标题栏的样式
-
"enablePullDownRefresh": true //表示开启下拉刷新 -
"navigationBarTitleText": "爱宠吧-首页", //表示设置标题内容 -
"pages": [ { "path": "pages/home/home", "style": { "navigationBarTitleText": "爱宠吧-首页", "enablePullDownRefresh": true //表示开启下拉刷新 } }, { "path": "pages/cate/cate", "style": { "navigationBarTitleText": "爱宠吧-分类", "enablePullDownRefresh": true } }, { "path": "pages/cart/cart", "style": { "navigationBarTitleText": "爱宠吧-购物车", "enablePullDownRefresh": true } }, { "path": "pages/my/my", "style": { "navigationBarTitleText": "爱宠吧-个人", "enablePullDownRefresh": true } } ],
-
一些对于uni顶级对象的使用
网络请求的配置
- 微信小程序不支持axios
- 官方文档@escook/request-miniprogram - npm (npmjs.com)

//初始化第三方包管理的配置文件
npm init -y
//这样会生成一个第三方的包管理文件package.json,里面是第三方包的相关信息
//首先安装第三方数据包
npm install @escook/request-miniprogram
//导入网络请求包
import {$http} from '@escook/request-miniprogram'
//将导入的对象挂载到微信小程序的顶级wx对象中,而是用uni-app,则对象为uni
uni.$http = $http
//第一个$http表示设置一个uni对象的属性名字,第二个$http表示是我导入的第三方包的名字,作为值传递给uni对象的$http属性
//之后直接使用uni.$http就可以直接发送请求
// 发起 GET 请求,data 是可选的参数对象
uni.$http.get(url, data?)
// 发起 POST 请求,data 是可选的参数对象
uni.$http.post(url, data?)
// 发起 PUT 请求,data 是可选的参数对象
uni.$http.put(url, data?)
// 发起 DELETE 请求,data 是可选的参数对象
uni.$http.delete(url, data?)
//在main.js文件中设置请求的根路径
$http.baseUrl = 'https://www.example.com'
//配置请求拦截器,请求开始前做一些动作
$http.beforeRequest = function (options) {
// do somethimg...
uni.showLoading({
title: '数据加载中...',
})
} //设置加载效果,自定义请求头等
//响应拦截器,请求完成之后做一些事情
$http.afterRequest = function () {
// do something...
uni.hideLoading({
title: '数据加载中...',
})
} //设置加载效果隐藏
配置一个自定义的请求反映效果
//数据请求失败提示
uni.$showMsg = function(title = '请求失败',duration = 1500){
uni.showToast({
title,//表示显示内容
duration,//表示显示时间
icon:'none' //表示没图标
})
}
调用时候直接使用uni.$showMsg
showToast方法是uni中的弹窗方法
这里设置了一个uni的自定义属性,这样就可以实现全局使用这个弹窗提示,而不用每次都写
配置在main.js中
使用变量的方式
在标签中属性绑定值
<view :style="{height: wh + 'px'}" :scroll-top="scropTop"></view>
<script>
export default {
data() {
return {
//这里就是设置的变量
active: 0,
wh: 0,
typelist: [],
typelist2: [],
scropTop:0
};
}
</script>
在js代码中使用变量,用this调用
onLoad() {
const sync = uni.getSystemInfoSync().windowHeight
this.wh = sync
this.getlist()
},
一些标签和用法的解释使用
轮播图代码块
使用uswiper生成一个代码块
:indicator-dots是小圆点
:autoplay="true"是自动播放
:interval="3000"是播放间隔
:duration="1000"是停留时间
:circular="true"衔接滚动
<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
<swiper-item v-for="(item,i) in swiperlist" :key="i">
<navigator class="swiper" :url="'/subpacking/goods_list/goods_list'">
<image :src="item.url"></image>
</navigator>
</swiper-item>
</swiper>
导航组件
<navigator class="swiper" :url="'/subpacking/goods_list/goods_list'">
<image :src="item.url"></image>
</navigator>
navigator组件是可以进行导航跳转的组件
页面跳转
uni.navigateTo({
url:'/subpacking/goods/goods?goods_id='+goods.goods_id
})
这里跳转携带着参数
使用switchTab进行页面跳转时候,不能传递参数
uni.switchTab({
url: "/pages/order/order"
})
滑动组件
<scroll-view scroll-y="true"></scroll-view>
这里设置的是纵向滚动
底部导航栏设置
"tabBar": {
"selectedColor": "#0000ff",
"list": [{
"pagePath": "pages/home/home",
"text": "首页",
"iconPath": "/static/index.png", //表示未选择时
"selectedIconPath": "/static/index-fill.png" //表示选择时
},
{
"pagePath": "pages/cart/cart",
"text": "购物车",
"iconPath": "/static/love.png",
"selectedIconPath": "/static/love (1).png"
},
{
"pagePath": "pages/cate/cate",
"text": "文创",
"iconPath": "/static/wenchuang.png",
"selectedIconPath": "/static/wenchuangxuanzhong.png"
},
{
"pagePath": "pages/my/my",
"text": "我的",
"iconPath": "/static/mine.png",
"selectedIconPath": "/static/mine (1).png"
}
]
},
组件官网
获取设备信息
系统信息的概念 | uni-app官网 (dcloud.net.cn)
uni.getSystemInfoSync(),这个方法获取设备信息
通过创建的props对象自定义属性
<template>
<view class="my-search" :style="{'background-color': bgcolor}" @click="searchBox">
<view class="my-search-main" :style="{'border-radius':radius + 'px'}">
<uni-icons type="search" size="17"></uni-icons>
<text class="placeholder">搜索</text>
</view>
</view>
</template>
<script>
export default {
name:"my-search",
//通过props实现自定义属性
props:{
//背景颜色
bgcolor:{
type:String,
default:'#ff0000'
},
//圆角
radius:{
type:Number,
default:18
}
},
data() {
return {
};
},
}
}
</script>
1.自定义属性,封装通用组件时候,可以极大提高组件的复用性
2.default属性,可以设置初始值,当外界不调用自定义对象赋初值时候,默认有一个值
3.type属性,用于设置自定义属性的数据类型,注意:如果type是一个object对象,,default属性就要封装为一个函数,通过return返回默认值
自定义组件的自定义属性的调用
<my-search bgcolor="#cccccc" radius="20"></my-search>
自定义组件无法使用@click的问题解决
由于自定义组件无法实现@click绑定,就需要在其内部元素中邦迪一个click点击事件处理函数
以下是一个自定义组件的示例
<template>
<view class="my-search" :style="{'background-color': bgcolor}" @click="searchBox">
</view>
</template>
@click="searchBox"绑定了一个searchBox事件,以下是函数实现
methods:{
searchBox(){
//要有emit存在,才能在使用组件页面中,实现响应点击方法,括号里面是方法名字
this.$emit('click')
}
}
这里使用了$emit,通过这个方法,传递要绑定的功能的名字,就实现了自定义事件,在这里,由于searchBox是通过点击实现,所以这个自定义事件功能就是鼠标点击事件
之后是自定义组件中事件的调用
<my-search @click="gotoSearch"></my-search>
gotoSearch是设置的一个点击实现的方法
防抖处理
data() {
return {
//防抖设置
timer: null,
kw: '',
};
}
input(e) {
//设置防抖,目的是为了减少资源消耗,防止input操作每次都打印内容
//因为定时器timeout只会执行一次,所以需要清除后重新开始
clearTimeout(this.timer)
//设置定时器,用于进行文本输出,延迟0.5s输出
this.timer = setTimeout(() => {
this.kw = e
this.getSearchList()
//因为没有接口数据先放这里,原本放在获取建议后
this.saveSearchHistory()
}, 500) 表示500毫秒后无动作,便执行定时器内容,每次输入,只要输入没有停止,就不会触发定时器
},
上拉触底和下拉刷新
这里需要在pages.json中设置
"subPackages": [{
"root": "subpacking", //根目录设定
"pages": [
{
"path": "goods/goods",
"style": {
"navigationBarTitleText": "",
"enablePullDownRefresh": false
}
},
{
"path" : "search/search",
"style" : {
"navigationBarTitleText": "",
"enablePullDownRefresh": false
}
},
{
"path" : "goods_list/goods_list",
"style" :{
"navigationBarTitleText": "",
"enablePullDownRefresh": true,//开启下拉刷新
// 设置上拉触底距离
"onReachBottomDistance": 150,
"backgroundColor": "#b8c3dd"//下拉刷新的背景颜色
}
}
]
}]
与methods结点平行,书写两个方法
//上拉触底效果,更新列表
onReachBottom() {
if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕')
if (this.isloding === false) {
// 页面加一
this.queryObj.pagenum += 1
// 重新获取列表
this.getgoodlist()
}
},
//下拉刷新
onPullDownRefresh() {
this.queryObj.pagenum = 1
this.total = 0
this.isloding = false
this.goodslist = []
this.getgoodlist(()=>{
uni.stopPullDownRefresh()
})
书写uni.stopPullDownRefresh()在onPullDownRefresh()函数里面,就可以实现刷新之后的停止刷新
}
富文本
绑定的数据是带有样式的html字符串,使用富文本可以将其渲染出来
<!-- 获取的数据是一串html文件,富文本就可以渲染出他们 -->
<rich-text :nodes="goods_info.goods_introduce"></rich-text>
字符串的替换
// 使用字符串的replace()方法,为img标签添加行内css属性,从而解决图片底部空白间隙的问题,g代表全局替换
res.message.goods_introduce = res.message.goods_introduce.replace(/<img /g,
'<img style = "display:block;"')
数据全局共享
-
首先在根目录下建立store目录,新建store.js
1.书写要进行全局共享的数据.js文件 export default{ //为模块开启命名空间 namespaced:true, state:()=>({ //这是购物车数组,用于存储购物车商品信息 cart:[] }), mutations:{}, getters:{} //注意,state里面的数据只能被mutations里面的方法修改 } 2.导入vue和vuex和自己书写的js文件 import Vue from 'vue' import Vuex from 'vuex' import moduleCart from '@/store/cart.js' 3.将vuex安装为vue的一个插件 Vue.use(Vuex) 4.创建store实例对象 const store = new Vuex.Store({ //挂载store的模块 modules:{ //引入自己书写的.js文件 '书写的模块对象名':导入的模块名 } }) 5.向外共享store对象 export default store 6.在main.js中导入实例对象,并挂载在vue实例上 import store from '@/store/store.js' const app = new Vue({ ...App, store }) //全局对象的使用 7.在要使用的模块的.vue文件里面导入vuex辅助函数 import {mapState} from 'vuex' //与data节点平级设置计算属性 computed:{...mapState('m_cart',[])}, //...是展开运算可以不管,'m_cart'是在store.js全局文件中书写的模块对象名
数据的持久化

export default{
//为模块开启命名空间
namespaced:true,
state:()=>({
//这是购物车数组,用于存储购物车商品信息
cart:JSON.parse(uni.getStorageSync('cart') || '[]')
//通过json提供的转化方法,转为数组,动态更新转换的购物车
}),
mutations:{
addToCart(state,goods){
const Result = state.cart.find(x=>x.goods_id === goods.goods_id)
if(!Result){
state.cart.push(goods)
}else{
Result.goods_count++
}
//这里是本地的提交,提交的是'm_cart'下的saveToStorage
this.commit('m_cart/saveToStorage')
},
//这里是调用uni提供的API进行本地存储,json同样是用来转换为字符串格式
saveToStorage(state){
uni.setStorageSync('cart',JSON.stringify(state.cart))
}
},
getters:{
total(state){
let c = 0;
state.cart.forEach(goods => c+=goods.goods_count)
return c
}
}
}
小程序的分包配置
定义:有利于减少小程序首次启动时的加载时间
将tabBar导航栏有关页面放置在主包中,其他的放置在分包中
分包配置过程
创建分包根目录,命名为subpackage
在page.json中与pages结点平级声明subPackages结点
最后在subpackage目录中创建页面
创建页面后,在pages.json中就会自动有页面信息加载
"subPackages": [{ "root": "subpacking", //根目录设定 "pages": [ { "path": "goods/goods", "style": { "navigationBarTitleText": "", "enablePullDownRefresh": false } }, { "path" : "search/search", "style" : { "navigationBarTitleText": "", "enablePullDownRefresh": false } }, { "path" : "goods_list/goods_list", "style" :{ "navigationBarTitleText": "", "enablePullDownRefresh": true, // 设置上拉触底距离 "onReachBottomDistance": 150, "backgroundColor": "#b8c3dd" } } ] }]
设置统一请求头

这样设置之后,就可以通过api/接口名/参数的形式进行接口的调用,这里也设置了跨域
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)