uniapp前端开发,基于vue3,element plus组件库,以及axios通讯

[复制链接]
发表于 2025-12-19 21:18:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
简介

UniApp 是一个基于 Vue.js 的跨平台开发框架,旨在通过一次开发、编译后运行在多个平台上,如 iOS、Android、H5、以及小步调(微信小步调、付出宝小步调、百度小步调等)等。UniApp 为开发者提供了同一的开发体验,使得同一套代码可以在多个平台上运行,从而镌汰开发和维护本钱。
根本上可以直接使用vue的语法,为了可移植性,以是大部分的东西都是用的vue的,少部分,像页面导航,使用uniapp自带的
vue

设置

换淘宝源
  1. npm config set registry https://registry.npm.taobao.org
复制代码
下载
  1. npm install -g @vue/cli
  2. npm uninstall -g @vue/cli
复制代码
创建项目
  1. vue create vue01
复制代码
如果创建碰到报错
  1. error Error: certificate has expired
复制代码
关闭strict-ssl后再安装
  1. yarn config set strict-ssl false
复制代码
cd到工程目次之后
  1. npm run dev
复制代码
存储

localStorage

恒久有效
  1. <template>
  2.   <div>
  3.     <input v-model="username" placeholder="输入用户名" />
  4.     <button @click="saveUsername">保存用户名</button>
  5.     <p>存储的用户名:{{ storedUsername }}</p>
  6.   </div>
  7. </template>
  8. <script setup>
  9. import { ref, onMounted } from 'vue';
  10. // 定义数据
  11. const username = ref('');
  12. const storedUsername = ref('');
  13. // 保存用户名到 localStorage
  14. const saveUsername = () => {
  15.   localStorage.setItem('username', username.value);
  16.   storedUsername.value = username.value;
  17. };
  18. // 获取存储的用户名
  19. onMounted(() => {
  20.   const savedUsername = localStorage.getItem('username');
  21.   if (savedUsername) {
  22.     storedUsername.value = savedUsername;
  23.   }
  24. });
  25. </script>
复制代码
sessionStorage

关闭欣赏器后失效,跟本地存储类似
设置数据到 sessionStorage:
  1. sessionStorage.setItem('sessionData', 'someValue');
复制代码
获取 sessionStorage 中的数据:
  1. const sessionData = sessionStorage.getItem('sessionData');
  2. console.log(sessionData); // 'someValue'
复制代码
删除 sessionStorage 中的数据:
  1. sessionStorage.removeItem('sessionData');
复制代码
清空 sessionStorage 中的全部数据:
  1. sessionStorage.clear();
复制代码
生命周期钩子

可以在页面开始挂载时,举行一些利用,如开始监听消息,添补默认数据等
  1. <template>
  2.   <div>
  3.     <p>当前时间:{{ currentTime }}</p>
  4.     <button @click="stopTimer">停止计时</button>
  5.   </div>
  6. </template>
  7. <script setup>
  8. import { ref, onMounted, onBeforeUnmount } from 'vue';
  9. const currentTime = ref('');
  10. let timer = null;
  11. // 组件挂载后开始计时
  12. onMounted(() => {
  13.   timer = setInterval(() => {
  14.     currentTime.value = new Date().toLocaleTimeString();
  15.   }, 1000);
  16. });
  17. // 组件销毁之前清除定时器
  18. onBeforeUnmount(() => {
  19.   clearInterval(timer);
  20. });
  21. </script>
复制代码
route

uniapp中路由使用自带的uni.navigateTo()跳转
  1. npm install vue-router@4
复制代码
uniapp

页面跳转

pageA
  1. <!-- pageA.vue -->
  2. <template>
  3.   <view>
  4.     <button @click="goToPageBWithParams">跳转到页面B并传递参数</button>
  5.     <button @click="goToPageB">跳转到页面B不传递参数</button>
  6.   </view>
  7. </template>
  8. <script setup>
  9. import { ref } from 'vue';
  10. const goToPageBWithParams = () => {
  11.   uni.navigateTo({
  12.     url: '/pages/pageB/pageB?name=John&age=25'
  13.   });
  14. };
  15. const goToPageB = () => {
  16.   uni.navigateTo({
  17.     url: '/pages/pageB/pageB'
  18.   });
  19. };
  20. </script>
复制代码
pageB
  1. <!-- pageB.vue -->
  2. <template>
  3.   <view>
  4.     <text v-if="name && age">名字:{{ name }}, 年龄:{{ age }}</text>
  5.     <text v-else>没有接收到参数</text>
  6.   </view>
  7. </template>
  8. <script setup>
  9. import { ref, onMounted } from 'vue';
  10. import { useRoute } from 'vue-router';
  11. const name = ref('');
  12. const age = ref('');
  13. onMounted(() => {
  14.   const route = useRoute();
  15.   
  16.   // 获取查询参数
  17.   name.value = route.query.name || '';
  18.   age.value = route.query.age || '';
  19. });
  20. </script>
复制代码
也可以使用页面栈来获取查询参数
  1.   // 获取当前页面的 query 参数
  2.   const pages = getCurrentPages();
  3.   const currentPage = pages[pages.length - 1];
  4.   const { name: pageName, age: pageAge } = currentPage.options;
  5.   name.value = pageName || '';
  6.   age.value = pageAge || '';
复制代码
页面栈

在 UniApp 中,页面栈是管理页面之间跳转和返回的一个告急机制。每次打开一个新页面,当前页面会被压入栈中,新的页面会成为栈顶的页面。当用户返回时,栈顶的页面被移除,返回到之前的页面。UniApp 的页面栈管理类似于欣赏器的汗青记载机制。以下是一些重要概念:

  • 页面栈限定
UniApp 的页面栈最多答应 10 层页面(这可以通过 H5 端的history模式来拓展),凌驾限定时,会主动将底部的页面出栈,从而保持页面栈的数目。

  • 页面跳转方式


  • uni.navigateTo: 进入新页面时,新页面会被压入页面栈,当前页面保持在栈中,恰当在栈内管理跳转。
  • uni.redirectTo: 更换当前页面,不会生存当前页面到栈中,实用于不渴望用户返回之前页面的场景。
  • uni.reLaunch: 清空整个页面栈,打开指定的页面,一样寻常用于登录页面、首页等。
  • uni.switchTab: 切换到tabBar页面,不会涉及页面栈管理,由于tabBar页面是独立的。

  • 页面返回


  • uni.navigateBack: 返回上一个页面,默认返回一层,可以通过传入参数指定返回的页面层级。

  • 生命周期与页面栈的关系
每当页面栈发生变革,页面生命周期函数也会相应地触发:


  • onLoad: 页面第一次加载时触发。
  • onShow: 每次页面表现时触发,包罗返回时。
  • onHide: 页面潜伏时触发,通常是在页面跳转到其他页面时触发。
这种页面栈机制资助开发者在管理多页面应用时,更好地控制页面间的导航和返回利用。
如果有详细的应用场景或题目,也可以进一步探究怎样使用页面栈。
可以用如下代码打印关于页面栈的信息
  1.   // 获取当前页面栈
  2.   const pages = getCurrentPages();
  3.   
  4.   // 打印页面栈
  5.   console.log(pages);
  6.   
  7.   // 打印页面栈的长度(当前打开的页面数量)
  8.   console.log("页面栈长度: ", pages.length);
  9.   
  10.   // 获取栈顶页面(当前显示的页面)
  11.   const currentPage = pages[pages.length - 1];
  12.   console.log("当前页面路径: ", currentPage.route);
  13.   console.log("当前页面参数: ", currentPage.options);
复制代码
Element plus

简介

一个基于vue3组件库,挺悦目标.嗯
设置

安装
  1. npm install element-plus
复制代码
修改设置文件main.js中vue3部分
  1. import App from './App'
  2. import { createSSRApp } from 'vue'
  3. import ElementPlus from 'element-plus'
  4. import 'element-plus/dist/index.css'
  5. export function createApp() {
  6.   const app = createSSRApp(App)
  7.   app.use(ElementPlus) // 挂载 ElementPlus
  8.   return {
  9.     app
  10.   }
  11. }
复制代码
示例代码

  1. <template>
  2.   <div>
  3.     <el-input v-model="inputValue" placeholder="请输入内容" style="width: 300px;"></el-input>
  4.     <el-button type="primary" @click="handleClick" style="margin-left: 10px;">提交</el-button>
  5.     <p>输入的内容:{{ inputValue }}</p>
  6.   </div>
  7. </template>
  8. <script setup>
  9. import { ref } from 'vue';
  10. const inputValue = ref('');
  11. const handleClick = () => {
  12.   alert(`你输入的内容是:${inputValue.value}`);
  13. };
  14. </script>
复制代码
图标库

  1. npm install @element-plus/icons-vue
复制代码
使用
  1. <template>
  2.   <div>
  3.     <el-button type="primary">
  4.                 <el-icon>
  5.                   <search />
  6.                 </el-icon>     
  7.       搜索
  8.     </el-button>
  9.     <el-button type="success">
  10.                 <el-icon>
  11.                   <edit />
  12.                 </el-icon>     
  13.       编辑
  14.     </el-button>
  15.     <el-button type="danger">
  16.                 <el-icon>
  17.                   <delete />
  18.                 </el-icon>
  19.        删除
  20.     </el-button>
  21.     <el-button>
  22.       <el-icon>
  23.         <refresh />
  24.       </el-icon>
  25.       刷新
  26.     </el-button>
  27.     <el-button type="warning">
  28.       <el-icon>
  29.         <share />
  30.       </el-icon>
  31.       分享
  32.     </el-button>
  33.   </div>
  34. </template>
  35. <script setup>
  36. import { Search, Edit, Delete, Refresh, Share } from '@element-plus/icons-vue';
  37. import { ElButton, ElIcon } from 'element-plus';
  38. </script>
复制代码
axios

简介

用于前后端互换数据,通过url与后端毗连
url

一个完备的URL(Uniform Resource Locator,同一资源定位符)通常由以下几个部分构成:

  • 协议(Scheme/Protocol)

    • 界说访问资源所用的协议,比方http、https、ftp等。
    • 格式:http://或https://

  • 域名(Domain Name)或IP地点

    • 标识资源地点的服务器地点,比方www.example.com或192.168.1.1。
    • 也可以包罗www子域,或是更详细的子域名如blog.example.com。

  • 端标语(Port)

    • 指定服务器上运行的特定服务的端口,默以为80(HTTP)或443(HTTPS),通常省略。
    • 格式::8080

  • 路径(Path)

    • 服务器上资源的详细位置,通常类似于文件体系路径,如/folder/page.html。
    • 如果没有路径,通常默认指向网站的根目次。

  • 查询参数(Query Parameters)

    • 包罗键值对,用于转达给资源的参数,通常用于动态页面或API哀求。
    • 动态页面如根据id表现差别的界面,API哀求如rest风格的接口
    • 一样寻常在get内里定位资源,在post内里应用一样寻常都是API版本控制、分页、身份验证、路径增补、兼容性支持等场景,以便保持API接口的划一性和简便性。
    • 格式:?key1=value1&key2=value2

  • 片断标识符(Fragment Identifier)

    • 指向资源内的某个位置,如页面内的锚点。
    • 在wiki百科中经常用到定位某个标签https://en.wikipedia.org/wiki/Wiki#Conferences
    • 格式:#section1

示例URL:
  1. https://www.example.com:8080/folder/page.html?search=query#section1
复制代码
设置

  1. npm i axios
复制代码
示例

  1. <template>
  2.   <div>
  3.     <div @click="fetchData" class="box">Click me to GET data</div>
  4.     <button @click="sendData">Send POST Request</button>
  5.     <div v-if="data">
  6.       <h3>Data from GET request:</h3>
  7.       <pre>{{ data }}</pre>
  8.     </div>
  9.        
  10.     <div v-if="postResponse">
  11.       <h3>Response from POST request:</h3>
  12.       <pre>{{ postResponse }}</pre>
  13.     </div>
  14.   </div>
  15. </template>
  16. <script setup>
  17. import axios from 'axios'
  18. import { ref } from 'vue'
  19. const data = ref(null)
  20. const postResponse = ref(null)
  21. async function fetchData() {
  22.   try {
  23.     const res = await axios.get("http://localhost:8088/user/list")
  24.     data.value = res.data
  25.     console.log(res, "Data received from GET request")
  26.   } catch (error) {
  27.     console.error("Error fetching data:", error)
  28.   }
  29. }
  30. async function sendData() {
  31.   try {
  32.     const payload = { key: 'value' } // Replace with actual data to send
  33.     const res = await axios.post("http://localhost:8088/user/add", payload)
  34.     postResponse.value = res.data
  35.     console.log(res, "Data received from POST request")
  36.   } catch (error) {
  37.     console.error("Error sending data:", error)
  38.   }
  39. }
  40. </script>
  41. <style scoped>
  42. .box {
  43.   cursor: pointer;
  44.   padding: 10px;
  45.   background-color: #f0f0f0;
  46.   border: 1px solid #ccc;
  47.   text-align: center;
  48. }
  49. </style>
复制代码
库封装

由于必要许多与后端的接口,以是我们举行封装,镌汰调用复杂度
  1. import axios from 'axios';
  2. import { ElMessage } from 'element-plus';
  3. // 创建axios实例
  4. const http = axios.create({
  5.   baseURL: 'http://localhost:8080', // 设置基础URL
  6.   timeout: 5000, // 设置超时时间
  7. });
  8. // 请求拦截器
  9. http.interceptors.request.use(
  10.   config => {
  11.     // 在请求发送之前做些什么,比如添加 token 等
  12.     // config.headers.Authorization = `Bearer ${getToken()}`;
  13.     return config;
  14.   },
  15.   error => {
  16.     // 请求错误处理
  17.     ElMessage.error('请求发送失败');
  18.     return Promise.reject(error);
  19.   }
  20. );
  21. // 响应拦截器
  22. http.interceptors.response.use(
  23.   response => {
  24.     // 处理响应成功
  25.     if (response.status === 200) {
  26.       return response.data;
  27.     }
  28.     ElMessage.error('服务器异常');
  29.     return Promise.reject(response);
  30.   },
  31.   error => {
  32.     // 处理响应失败
  33.     const status = error.response ? error.response.status : null;
  34.     if (status === 404) {
  35.       ElMessage.error('请求的资源未找到');
  36.     } else if (status === 500) {
  37.       ElMessage.error('服务器内部错误');
  38.     } else {
  39.       ElMessage.error('网络错误,请稍后重试');
  40.     }
  41.     return Promise.reject(error);
  42.   }
  43. );
  44. // 封装常用请求方法
  45. export const get = (url, params = {}) => http.get(url, { params });
  46. export const post = (url, data = {}) => http.post(url, data);
  47. export const put = (url, data = {}) => http.put(url, data);
  48. export const del = (url, data = {}) => http.delete(url, { data });
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表