当前位置:   article > 正文

uniapp创建vue3项目_uniapp vue3

uniapp vue3

一.项目全局配置

1. 创建项目

使用Hbuilderx工具创建项目,

使用Hbuilderx工具创建项目,选择uni-ui项目模版,VUE3

2.底部菜单栏配置tabBar

uniapp官网: 全局文件--pages.json页面路由 -- tabBar

项目文件:pages.json--文件底部添加,list配置2-5

  1. "tabBar": {
  2. "color": "#7A7E83",
  3. "selectedColor": "#3cc51f",
  4. "borderStyle": "black",
  5. "backgroundColor": "#ffffff",
  6. "list": [{
  7. "pagePath": "pages/index/index",
  8. "iconPath": "static/c1.png",
  9. "selectedIconPath": "static/c2.png",
  10. "text": "首页"
  11. }, {
  12. "pagePath": "pages/index2/index",
  13. "iconPath": "static/c3.png",
  14. "selectedIconPath": "static/c4.png",
  15. "text": "页面"
  16. }]
  17. }

注:配置tabBar时所加页面一定要在pages中注册,否则会报错

报错:app.json: "tabBar"["pagePath"]: "pages/index2/index" need in ["pages"]

3.路由配置

app.json文件 -- pages页面配置项

4.全局样式配置

uniapp官网: 全局文件--pages.json页面路由 -- globalStyle

app.json文件 -- globalStyle

5.VUEX配置

store-->index.js

  1. // 页面路径:store/index.js
  2. import { createStore } from 'vuex'
  3. // import moduleA from '@/store/modules/moduleA'
  4. const store = createStore({
  5. state:{},
  6. getters: {},
  7. mutations: {},
  8. actions: {},
  9. modules: {
  10. // moduleA
  11. }
  12. })
  13. export default store

main.js 文件挂载全局

Vue2/Vue3配置根据文档来修改

6.全局样式配置

uni-scss文件

7.请求接口封装

api -- reuest.js

  1. const http = {
  2. // baseUrl 地址
  3. baseUrl: 'http://192.168.0.1:28002',
  4. // 请求方法
  5. request(config) {
  6. // config:请求配置对象,具体参照uniapp文档
  7. config = beforeRequest(config)
  8. // 请求地址拼接
  9. config.url = this.baseUrl + config.url
  10. // 异步请求
  11. return new Promise((resolve, reject) => {
  12. uni.request(config).then(res => { // 成功
  13. let [error, resp] = res
  14. // 响应拦截
  15. const response = beforeResponse(resp)
  16. resolve(response)
  17. }).catch(err => { // 失败
  18. errorHandle(err)
  19. reject(err)
  20. })
  21. })
  22. },
  23. get(url, data, auth) {
  24. /*
  25. url:接口地址
  26. data:查询参数
  27. auth:请求是否携带token进行认证(true/false)
  28. method:请求方式
  29. */
  30. return this.request({
  31. url: url,
  32. data: data,
  33. auth: auth,
  34. timeout:10000,
  35. method: 'GET'
  36. })
  37. },
  38. post(url, data, auth) {
  39. /*
  40. url:接口地址
  41. data:请求体参数
  42. auth:请求是否携带token进行认证(true/false)
  43. method:请求方式
  44. */
  45. return this.request({
  46. url: url,
  47. data: data,
  48. auth: auth,
  49. timeout:10000,
  50. method: 'POST'
  51. })
  52. },
  53. put(url, data, auth) {
  54. /*
  55. url:接口地址
  56. data:请求体参数
  57. auth:请求是否携带token进行认证(true/false)
  58. method:请求方式
  59. */
  60. return this.request({
  61. url: url,
  62. data: data,
  63. auth: auth,
  64. timeout:10000,
  65. method: 'PUT'
  66. })
  67. },
  68. delete(url, data, auth) {
  69. /*
  70. url:接口地址
  71. auth:请求是否携带token进行认证(true/false)
  72. method:请求方式
  73. */
  74. return this.request({
  75. url: url,
  76. auth: auth,
  77. timeout:10000,
  78. method: 'DELETE'
  79. })
  80. }
  81. }
  82. // 请求拦截器
  83. const beforeRequest = (config) => {
  84. // 请求之前拦截操作
  85. console.log('请求拦截器', config)
  86. return config
  87. }
  88. // 响应拦截器
  89. const beforeResponse = (response) => {
  90. // 请求之后操作
  91. console.log('响应拦截器', response)
  92. return response
  93. }
  94. // 请求异常处理器
  95. const errorHandle = ((err) => {
  96. console.log('请求异常', err)
  97. })
  98. export default http

​ ​api -- index.js

  1. // 封装具体接口调用
  2. import http from 'request.js'
  3. export default{
  4. // 登陆接口
  5. login(params){
  6. return http.post('/api/users/login',params)
  7. }
  8. // 注册接口
  9. // 刷新token
  10. // 获取用户信息
  11. // 获取信息
  12. }

挂载全局$api方法

  1. // 导入封装的请求对象
  2. import api from '@/api/index.js'
  3. // 将请求对象设置为全局属性
  4. Vue.prototype.$api = api

使用

  1. async fn(){
  2. const response = await this.$api.login()
  3. }

使用模块,写法用法变化

  1. api -- index.js
  2. // 封装具体接口调用
  3. import http from 'request.js'
  4. import user from './modules/user.js'
  5. import goods from './modules/goods.js'
  6. export default{
  7. user,
  8. goods
  9. }

使用

  1. async fn(){
  2. const response = await this.$api.user.login()
  3. }

二.主要功能实现

1.tabBar导航页面实现,主要页面实现

2.登陆功能实现,token及登陆状态

uni.login 微信登录

1.校验判断

2.调用登录接口,存储登陆的用户信息

saveLoginInfo(){} 存储登陆信息 存储token和refresh,userInfo ​ isAuth 是否登录

3.数据缓存,持久化

  1. // 数据持久化,存储到缓存中
  2. uni.setStorage({
  3. key: 'token',
  4. data: userInfo.token
  5. });
  6. uni.setStorage({
  7. key: 'isAuth',
  8. data: isAuth
  9. });
  10. uni.setStorage({
  11. key: 'refresh',
  12. data: userInfo.refresh
  13. });
  14. // 异步
  15. uni.setStorageSync('token', userInfo.token);

4.请求拦截器携带token

  1. // 请求拦截器
  2. const beforeRequest = (config) => {
  3. // 请求之前拦截操作
  4. console.log('请求拦截器', config)
  5. config.header = {}
  6. if (config.auth) {
  7. // 请求头中添加token
  8. if (uni.getStorageSync('token')) {
  9. // Authorization   Bearer   根据情况修改
  10. config.header['Authorization'] = 'Bearer' + uni.getStorageSync('token')
  11. } else {
  12. // 为登陆则跳转登陆 重定向
  13. uni.navigateTo({
  14. url: '/pages/index/index'
  15. })
  16. }
  17. }
  18. return config
  19. }

5.响应拦截器,错误信息提示

  1. // 响应拦截器
  2. const beforeResponse = (response) => {
  3. // 请求之后操作
  4. console.log('响应拦截器', response)
  5. // 判断请求返回的状态码
  6. if(response.status !== 200 && response.status !== 201 && response.status !== 204){
  7. // 给出对应的提示
  8. if(response.data.error){
  9. uni.showToast({
  10. title:response.data.error.toString(),
  11. icon:'none',
  12. duration:2000
  13. })
  14. }
  15. }
  16. return response
  17. }

6.VUEX刷新后数据丢失处理

App.vue ,根据需求更改

  1. <script>
  2. import {mapMutations} from 'vuex'
  3. export default {
  4. onLaunch: function() {
  5. console.warn('当前组件仅支持 uni_modules 目录结构 ,请升级 HBuilderX 到 3.1.0 版本以上!')
  6. console.log('App Launch')
  7. },
  8. onShow: function() {
  9. console.log('App Show')
  10. // 读取本地缓存,存储到VUEX中
  11. uni.getStorageSync('userInfo')
  12. // 调用保存登陆信息 操作
  13. // 存储相应的token,isAuth,userInfo等数据
  14. },
  15. onHide: function() {
  16. console.log('App Hide')
  17. },
  18. methods:{
  19. ...mapMutations(['保存登陆信息'])
  20. }
  21. }
  22. </script>

7.退出登陆效果

将登录时存储的数据清空,跳转相应的登陆页面或者首页

8.用户信息修改

调用相应的修改接口,拿到成功状态后更新VUEX用户信息及本地Storage存储的用户信息

3.登陆功能实现

  1. // 这里是vue2的写法,需要vue3请自行更换
  2. // 获取用户信息
  3. getWXCode() {
  4. return new Promise((ress, rej) => {
  5. // wx.login()
  6. uni.login({
  7. success: (res) => {
  8. res.code && ress(res.code)
  9. },
  10. fail: (error) => {}
  11. })
  12. })
  13. },
  14. //等三方微信登录 信息补充
  15. // 兑换code
  16. // 初始化 获取code 凭证
  17. wxLogin() {
  18. if (!this.checked) {
  19. // 是否勾选
  20. this.$utils.toast(0, '请先阅读并同意服务协议和隐私政策!')
  21. return
  22. }
  23. this.$utils.toast(1, "加载中")
  24. let that = this
  25. //#ifdef H5
  26. // #endif
  27. //#ifdef MP-WEIXIN
  28. this.getWXCode().then(res => {
  29. console.log("getWXCode", res)
  30. //成功后可根据实际情况自行处理
  31. // 判断用户是否注册,存储用户数据...
  32. })
  33. // #endif
  34. },

三.支付功能实现

1.微信

  1. // 此块代码放在vuex中(store.js)
  2. // 支付接口
  3. pay({
  4. commit
  5. }, param) {
  6. // console.log("param", param)
  7. return new Promise((resolve, reject) => {
  8. $utils.toast(1, "支付中")
  9. //#ifdef MP-WEIXIN
  10. const payParam = {
  11. appId: param.appId,
  12. nonceStr: param.nonceStr,
  13. package: param.packageVal,
  14. timeStamp: param.timeStamp,
  15. signType: param.signType,
  16. paySign: param.paySign,
  17. }
  18. //#endif
  19. //#ifdef MP-WEIXIN
  20. // console.log('MP-WEIXIN')
  21. uni.requestPayment({
  22. provider: 'wxpay',
  23. ...payParam,
  24. success: function(res) {
  25. console.log("支付成功---", res)
  26. // $utils.toast(1, "支付成功")
  27. setTimeout(() => {
  28. // $utils.toast(2)
  29. resolve(res)
  30. }, 1000)
  31. },
  32. fail: function(res) {
  33. console.log("支付失败---", res)
  34. // $utils.toast(0, "支付失败")
  35. resolve(res)
  36. },
  37. complete: function(res) {
  38. console.log("支付过程结束", res)
  39. // resolve(res)
  40. }
  41. });
  42. //#endif
  43. //#ifndef MP-WEIXIN
  44. WeixinJSBridge.invoke('getBrandWCPayRequest', {
  45. "appId": param.appId, //公众号名称,由商户传入
  46. "timeStamp": param.timeStamp, //时间戳
  47. "nonceStr": param.nonceStr, //随机串
  48. "package": param.package, //扩展包
  49. "signType": param.signType, //微信签名方式:MD5
  50. "paySign": param.paySign //微信签名
  51. }, function(respay) {
  52. // console.log('res', respay)
  53. if (respay.err_msg === "get_brand_wcpay_request:ok") {
  54. // 支付完成
  55. uni.showToast({
  56. title: "支付成功",
  57. icon: "none",
  58. duration: 2000
  59. })
  60. callback()
  61. } else if (respay.err_msg === "get_brand_wcpay_request:cancel") {
  62. $utils.toast(0, "取消支付")
  63. } else if (respay.err_msg === "get_brand_wcpay_request:fail") {
  64. $utils.toast(0, "支付失败")
  65. }
  66. }, function(err) {
  67. $utils.toast(0, err)
  68. })
  69. //#endif
  70. })
  71. }

2.支付宝

3.混合支付

四.工具函数封装

注:不全!需要其他的请自行搜索!

1.错误信息提示

注:根据后台需要提示接口错误还是前端自行提示!

  1. // 接口返回提示
  2. requestCodeTips(code, msg) {
  3. let errorrMessage = ''
  4. switch (Number(code)) {
  5. case 400:
  6. errorrMessage = '错误请求'
  7. break;
  8. case 401:
  9. errorrMessage = '未授权,请重新登录'
  10. break;
  11. case 403:
  12. errorrMessage = '拒绝访问'
  13. break;
  14. case 404:
  15. errorrMessage = '请求错误,未找到该资源'
  16. break;
  17. case 405:
  18. errorrMessage = '请求方法未允许'
  19. break;
  20. case 408:
  21. errorrMessage = '请求超时'
  22. break;
  23. case 500:
  24. errorrMessage = '服务器端出错啦'
  25. break;
  26. case 501:
  27. errorrMessage = '网络未实现'
  28. break;
  29. case 502:
  30. errorrMessage = '网络错误'
  31. break;
  32. case 503:
  33. errorrMessage = '服务不可用'
  34. break;
  35. case 504:
  36. errorrMessage = '网络超时'
  37. break;
  38. case 505:
  39. errorrMessage = 'http版本不支持该请求'
  40. break;
  41. default:
  42. errorrMessage = '连接错误'
  43. }
  44. this.toast(0, `${code}-${errorrMessage}-${msg?msg:''}`)
  45. },

2.全局提示信息(文本提示,加载状态)

  1. data: {
  2. msg: null, // 消息提示
  3. time: 300, // 时间
  4. hideLoadTimes: null, // 清除加载中的定时器
  5. showToastTimes: null, // 提示框的定时器
  6. },
  7. /**
  8. * * 提示信息
  9. * state: 类型 (0 提示框 1 showLoading 2 hideLoading )
  10. * title: 标题
  11. * duration: 时间
  12. * icon: 图标
  13. */
  14. async toast(state = 0, title = '', duration = 3000, icon = "none") {
  15. let errMsg = this.data.msg ? this.data.msg.errMsg : null
  16. if (state == 0) { //
  17. // 隐藏加载中的定时器还在
  18. if (this.data.hideLoadTimes || errMsg == 'showLoading:ok') {
  19. // 延后显示
  20. clearTimeout(this.data.showToastTimes)
  21. this.data.showToastTimes = setTimeout(async () => {
  22. this.data.msg = await uni.showToast({
  23. icon,
  24. title,
  25. duration,
  26. });
  27. this.data.showToastTimes = null
  28. }, this.data.time + 200)
  29. } else { // 隐藏加载中的定时器不能存在
  30. this.data.msg = await uni.showToast({
  31. icon,
  32. title,
  33. duration,
  34. });
  35. }
  36. } else if (state == 1) {
  37. this.data.time = this.data.time >= 900 ? 900 : this.data.time + 300
  38. this.data.msg = await uni.showLoading({
  39. title,
  40. mask: true
  41. });
  42. } else if (state == 2) {
  43. clearTimeout(this.data.hideLoadTimes)
  44. this.data.hideLoadTimes = setTimeout(async () => {
  45. this.data.msg = await uni.hideLoading();
  46. this.data.time = 300
  47. this.data.msg = null //
  48. this.data.hideLoadTimes = null
  49. }, this.data.time)
  50. }
  51. },

注:内容不全,缺少的话需要客官自行查询!谨慎食用哦!!!

相关文章:

1.前端环境变量配置

2.Axios封装_axios cdn链接

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/481385
推荐阅读
相关标签
  

闽ICP备14008679号