马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
简介
UniApp 是一个基于 Vue.js 的跨平台开发框架,旨在通过一次开发、编译后运行在多个平台上,如 iOS、Android、H5、以及小步调(微信小步调、付出宝小步调、百度小步调等)等。UniApp 为开发者提供了同一的开发体验,使得同一套代码可以在多个平台上运行,从而镌汰开发和维护本钱。
根本上可以直接使用vue的语法,为了可移植性,以是大部分的东西都是用的vue的,少部分,像页面导航,使用uniapp自带的
vue
设置
换淘宝源
- npm config set registry https://registry.npm.taobao.org
复制代码 下载
- npm install -g @vue/cli
- npm uninstall -g @vue/cli
复制代码 创建项目
如果创建碰到报错
- error Error: certificate has expired
复制代码 关闭strict-ssl后再安装
- yarn config set strict-ssl false
复制代码 cd到工程目次之后
存储
localStorage
恒久有效
- <template>
- <div>
- <input v-model="username" placeholder="输入用户名" />
- <button @click="saveUsername">保存用户名</button>
- <p>存储的用户名:{{ storedUsername }}</p>
- </div>
- </template>
- <script setup>
- import { ref, onMounted } from 'vue';
- // 定义数据
- const username = ref('');
- const storedUsername = ref('');
- // 保存用户名到 localStorage
- const saveUsername = () => {
- localStorage.setItem('username', username.value);
- storedUsername.value = username.value;
- };
- // 获取存储的用户名
- onMounted(() => {
- const savedUsername = localStorage.getItem('username');
- if (savedUsername) {
- storedUsername.value = savedUsername;
- }
- });
- </script>
复制代码 sessionStorage
关闭欣赏器后失效,跟本地存储类似
设置数据到 sessionStorage:
- sessionStorage.setItem('sessionData', 'someValue');
复制代码 获取 sessionStorage 中的数据:
- const sessionData = sessionStorage.getItem('sessionData');
- console.log(sessionData); // 'someValue'
复制代码 删除 sessionStorage 中的数据:
- sessionStorage.removeItem('sessionData');
复制代码 清空 sessionStorage 中的全部数据:
生命周期钩子
可以在页面开始挂载时,举行一些利用,如开始监听消息,添补默认数据等
- <template>
- <div>
- <p>当前时间:{{ currentTime }}</p>
- <button @click="stopTimer">停止计时</button>
- </div>
- </template>
- <script setup>
- import { ref, onMounted, onBeforeUnmount } from 'vue';
- const currentTime = ref('');
- let timer = null;
- // 组件挂载后开始计时
- onMounted(() => {
- timer = setInterval(() => {
- currentTime.value = new Date().toLocaleTimeString();
- }, 1000);
- });
- // 组件销毁之前清除定时器
- onBeforeUnmount(() => {
- clearInterval(timer);
- });
- </script>
复制代码 route
uniapp中路由使用自带的uni.navigateTo()跳转
uniapp
页面跳转
pageA
- <!-- pageA.vue -->
- <template>
- <view>
- <button @click="goToPageBWithParams">跳转到页面B并传递参数</button>
- <button @click="goToPageB">跳转到页面B不传递参数</button>
- </view>
- </template>
- <script setup>
- import { ref } from 'vue';
- const goToPageBWithParams = () => {
- uni.navigateTo({
- url: '/pages/pageB/pageB?name=John&age=25'
- });
- };
- const goToPageB = () => {
- uni.navigateTo({
- url: '/pages/pageB/pageB'
- });
- };
- </script>
复制代码 pageB
- <!-- pageB.vue -->
- <template>
- <view>
- <text v-if="name && age">名字:{{ name }}, 年龄:{{ age }}</text>
- <text v-else>没有接收到参数</text>
- </view>
- </template>
- <script setup>
- import { ref, onMounted } from 'vue';
- import { useRoute } from 'vue-router';
- const name = ref('');
- const age = ref('');
- onMounted(() => {
- const route = useRoute();
-
- // 获取查询参数
- name.value = route.query.name || '';
- age.value = route.query.age || '';
- });
- </script>
复制代码 也可以使用页面栈来获取查询参数
- // 获取当前页面的 query 参数
- const pages = getCurrentPages();
- const currentPage = pages[pages.length - 1];
- const { name: pageName, age: pageAge } = currentPage.options;
- name.value = pageName || '';
- age.value = pageAge || '';
复制代码 页面栈
在 UniApp 中,页面栈是管理页面之间跳转和返回的一个告急机制。每次打开一个新页面,当前页面会被压入栈中,新的页面会成为栈顶的页面。当用户返回时,栈顶的页面被移除,返回到之前的页面。UniApp 的页面栈管理类似于欣赏器的汗青记载机制。以下是一些重要概念:
UniApp 的页面栈最多答应 10 层页面(这可以通过 H5 端的history模式来拓展),凌驾限定时,会主动将底部的页面出栈,从而保持页面栈的数目。
- uni.navigateTo: 进入新页面时,新页面会被压入页面栈,当前页面保持在栈中,恰当在栈内管理跳转。
- uni.redirectTo: 更换当前页面,不会生存当前页面到栈中,实用于不渴望用户返回之前页面的场景。
- uni.reLaunch: 清空整个页面栈,打开指定的页面,一样寻常用于登录页面、首页等。
- uni.switchTab: 切换到tabBar页面,不会涉及页面栈管理,由于tabBar页面是独立的。
- uni.navigateBack: 返回上一个页面,默认返回一层,可以通过传入参数指定返回的页面层级。
每当页面栈发生变革,页面生命周期函数也会相应地触发:
- onLoad: 页面第一次加载时触发。
- onShow: 每次页面表现时触发,包罗返回时。
- onHide: 页面潜伏时触发,通常是在页面跳转到其他页面时触发。
这种页面栈机制资助开发者在管理多页面应用时,更好地控制页面间的导航和返回利用。
如果有详细的应用场景或题目,也可以进一步探究怎样使用页面栈。
可以用如下代码打印关于页面栈的信息
- // 获取当前页面栈
- const pages = getCurrentPages();
-
- // 打印页面栈
- console.log(pages);
-
- // 打印页面栈的长度(当前打开的页面数量)
- console.log("页面栈长度: ", pages.length);
-
- // 获取栈顶页面(当前显示的页面)
- const currentPage = pages[pages.length - 1];
- console.log("当前页面路径: ", currentPage.route);
- console.log("当前页面参数: ", currentPage.options);
复制代码 Element plus
简介
一个基于vue3组件库,挺悦目标.嗯
设置
安装
修改设置文件main.js中vue3部分
- import App from './App'
- import { createSSRApp } from 'vue'
- import ElementPlus from 'element-plus'
- import 'element-plus/dist/index.css'
- export function createApp() {
- const app = createSSRApp(App)
- app.use(ElementPlus) // 挂载 ElementPlus
- return {
- app
- }
- }
复制代码 示例代码
- <template>
- <div>
- <el-input v-model="inputValue" placeholder="请输入内容" style="width: 300px;"></el-input>
- <el-button type="primary" @click="handleClick" style="margin-left: 10px;">提交</el-button>
- <p>输入的内容:{{ inputValue }}</p>
- </div>
- </template>
- <script setup>
- import { ref } from 'vue';
- const inputValue = ref('');
- const handleClick = () => {
- alert(`你输入的内容是:${inputValue.value}`);
- };
- </script>
复制代码 图标库
- npm install @element-plus/icons-vue
复制代码 使用
- <template>
- <div>
- <el-button type="primary">
- <el-icon>
- <search />
- </el-icon>
- 搜索
- </el-button>
- <el-button type="success">
- <el-icon>
- <edit />
- </el-icon>
- 编辑
- </el-button>
- <el-button type="danger">
- <el-icon>
- <delete />
- </el-icon>
- 删除
- </el-button>
- <el-button>
- <el-icon>
- <refresh />
- </el-icon>
- 刷新
- </el-button>
- <el-button type="warning">
- <el-icon>
- <share />
- </el-icon>
- 分享
- </el-button>
- </div>
- </template>
- <script setup>
- import { Search, Edit, Delete, Refresh, Share } from '@element-plus/icons-vue';
- import { ElButton, ElIcon } from 'element-plus';
- </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:
- https://www.example.com:8080/folder/page.html?search=query#section1
复制代码 设置
示例
- <template>
- <div>
- <div @click="fetchData" class="box">Click me to GET data</div>
- <button @click="sendData">Send POST Request</button>
- <div v-if="data">
- <h3>Data from GET request:</h3>
- <pre>{{ data }}</pre>
- </div>
-
- <div v-if="postResponse">
- <h3>Response from POST request:</h3>
- <pre>{{ postResponse }}</pre>
- </div>
- </div>
- </template>
- <script setup>
- import axios from 'axios'
- import { ref } from 'vue'
- const data = ref(null)
- const postResponse = ref(null)
- async function fetchData() {
- try {
- const res = await axios.get("http://localhost:8088/user/list")
- data.value = res.data
- console.log(res, "Data received from GET request")
- } catch (error) {
- console.error("Error fetching data:", error)
- }
- }
- async function sendData() {
- try {
- const payload = { key: 'value' } // Replace with actual data to send
- const res = await axios.post("http://localhost:8088/user/add", payload)
- postResponse.value = res.data
- console.log(res, "Data received from POST request")
- } catch (error) {
- console.error("Error sending data:", error)
- }
- }
- </script>
- <style scoped>
- .box {
- cursor: pointer;
- padding: 10px;
- background-color: #f0f0f0;
- border: 1px solid #ccc;
- text-align: center;
- }
- </style>
复制代码 库封装
由于必要许多与后端的接口,以是我们举行封装,镌汰调用复杂度
- import axios from 'axios';
- import { ElMessage } from 'element-plus';
- // 创建axios实例
- const http = axios.create({
- baseURL: 'http://localhost:8080', // 设置基础URL
- timeout: 5000, // 设置超时时间
- });
- // 请求拦截器
- http.interceptors.request.use(
- config => {
- // 在请求发送之前做些什么,比如添加 token 等
- // config.headers.Authorization = `Bearer ${getToken()}`;
- return config;
- },
- error => {
- // 请求错误处理
- ElMessage.error('请求发送失败');
- return Promise.reject(error);
- }
- );
- // 响应拦截器
- http.interceptors.response.use(
- response => {
- // 处理响应成功
- if (response.status === 200) {
- return response.data;
- }
- ElMessage.error('服务器异常');
- return Promise.reject(response);
- },
- error => {
- // 处理响应失败
- const status = error.response ? error.response.status : null;
- if (status === 404) {
- ElMessage.error('请求的资源未找到');
- } else if (status === 500) {
- ElMessage.error('服务器内部错误');
- } else {
- ElMessage.error('网络错误,请稍后重试');
- }
- return Promise.reject(error);
- }
- );
- // 封装常用请求方法
- export const get = (url, params = {}) => http.get(url, { params });
- export const post = (url, data = {}) => http.post(url, data);
- export const put = (url, data = {}) => http.put(url, data);
- export const del = (url, data = {}) => http.delete(url, { data });
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金 |