以下是一个完整的 Uniapp 分包示例,代码分布在不同的文件夹中,其中包含了两个子包 sub1 和 sub2,以及一个主包 main。
在项目根目录下创建 pages 文件夹,并在其中创建各个页面的文件夹。
在每个页面文件夹中创建对应的 vue 文件和 js 文件。
在 pages.json 文件中定义各个页面和子包的信息。
- {
- "pages": [
- {
- "path": "pages/index/index",
- "style": {
- "navigationBarTitleText": "首页"
- }
- },
- {
- "path": "pages/sub1/index",
- "name": "sub1",
- "subPackage": true,
- "root": "pages/sub1/",
- "pages": [
- {
- "path": "page1/page1",
- "style": {
- "navigationBarTitleText": "子包1页面1"
- }
- },
- {
- "path": "page2/page2",
- "style": {
- "navigationBarTitleText": "子包1页面2"
- }
- }
- ]
- },
- {
- "path": "pages/sub2/index",
- "name": "sub2",
- "subPackage": true,
- "root": "pages/sub2/",
- "pages": [
- {
- "path": "page1/page1",
- "style": {
- "navigationBarTitleText": "子包2页面1"
- }
- },
- {
- "path": "page2/page2",
- "style": {
- "navigationBarTitleText": "子包2页面2"
- }
- }
- ]
- }
- ]
- }
在项目根目录下创建 static 目录,并在其中存放项目所需的静态资源文件。
在各个页面的 vue 文件中使用图片等资源时,使用相对路径或绝对路径引用即可。
- <template>
- <div class="index">
- <img src="../../static/logo.png" alt="logo">
- <h1>{{ title }}</h1>
- <p>{{ content }}</p>
- </div>
- </template>
-
- <script>
- export default {
- data() {
- return {
- title: '首页',
- content: '欢迎来到 Uniapp 分包示例'
- }
- }
- }
- </script>
-
- <style>
- /* 样式 */
- </style>
- import Vue from 'vue'
- import App from './App'
- import uniPages from '@/components/uni-pages/uni-pages.vue'
- import uniPageHeadComPlus from '@/components/uni-page-head-com-plus/uni-page-head-com-plus.vue'
-
- Vue.config.productionTip = false
-
- Vue.component('uni-pages', uniPages)
- Vue.component('uni-page-head-com-plus', uniPageHeadComPlus)
-
- App.mpType = 'app'
-
- const app = new Vue({
- ...App
- })
- app.$mount()