根据您的需求,下面是一个基于Vue 3的uniapp项目,使用Axios进行网络请求和Vue Router进行路由管理的多端适配demo,兼容H5、小程序、安卓、iOS平台,并包含分包的详细完整案例。

1. 项目搭建

使用Vue 3和Vite创建uniapp项目:

# 安装Vue CLI(如果尚未安装)
npm install -g @vue/cli

# 创建项目
npx degit dcloudio/uni-preset-vue#vite my-vue3-project

# 进入项目目录
cd my-vue3-project

# 安装依赖
npm install

2. 安装Axios和适配器

由于uniapp中不能直接使用Axios,需要安装适配器uniapp-axios-adapter:

npm install axios uniapp-axios-adapter

3. 封装Axios请求

在utils/request.js中封装Axios请求:

// utils/request.js
import axios from "axios";
import { UniAdapter } from "uniapp-axios-adapter";

const request = axios.create({
  baseURL: "https://example.com",
  timeout: 10000,
  adapter: UniAdapter, // 指定适配器
});

// 请求拦截器
request.interceptors.request.use((config) => {
  // 带上token
  config.headers["Authorization"] = "token";
  return config;
});

export default request;

4. 使用Axios请求

在页面中使用封装好的Axios请求:

// pages/index/index.vue
<template>
  <view>
    <button @click="fetchData">获取数据</button>
  </view>
</template>

<script>
import request from "@/utils/request";

export default {
  methods: {
    async fetchData() {
      try {
        const response = await request.get("/api/data");
        console.log(response.data);
      } catch (error) {
        console.error(error);
      }
    }
  }
};
</script>

5. 配置Vue Router

在Vue 3中,使用Vue Router进行路由管理:

// router/index.js
import { createRouter, createWebHistory } from "vue-router";

const routes = [
  {
    path: "/",
    name: "Home",
    component: () => import("@/pages/index/index.vue")
  },
  {
    path: "/detail",
    name: "Detail",
    component: () => import("@/pages/detail/detail.vue")
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

6. 在主入口文件中使用Router

// main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

const app = createApp(App);

app.use(router);

app.mount("#app");

7. 多端适配

uniapp天生支持多端适配,只需在pages.json中配置页面即可。对于特定平台的样式或逻辑,可以使用条件编译:

#ifdef H5
// H5平台特有代码
#endif

#ifdef MP-WEIXIN
// 小程序平台特有代码
#endif

8. 分包配置

在pages.json中配置分包信息:

{
  "pages": [
    // 主包页面配置
  ],
  "subPackages": [
    {
      "root": "pages/subPack",
      "pages": [
        {
          "path": "list",
          "style": {
            "navigationBarTitleText": "列表页",
            "enablePullDownRefresh": false
          }
        },
        {
          "path": "tab",
          "style": {
            "navigationBarTitleText": "标签页",
            "enablePullDownRefresh": false
          }
        }
      ]
    }
  ],
  // 其他配置...
}

9. 编译运行

在HBuilderX中编译运行小程序,检查是否能看到主包和分包(例如page2)的字样,以确认分包配置成功。

以上步骤展示了如何在uniapp项目中使用Vue 3、Axios和Vue Router进行多端适配开发,并包含分包配置。希望这个案例对你有所帮助。更多详细信息可以参考uniapp官方文档 uni-app开发指南。

更多推荐