Vue CLI3基础学习之pages构建多页应用
首先我们可以把多页应用理解为由多个单页构成的应用,而何谓多个单页呢?其实你可以把一个单页看成是一个 html 文件,那么多个单页便是多个 html 文件,多页应用便是由多个 html 组成的应用,如下图所示
既然多页应用拥有多个 html ,那么同样其应该拥有多个独立的入口文件、组件、路由、 vuex 等。没错,说简单一点就是多页应用的每个单页都可以拥有单页应用 src 目录下的文件及功能,我们来看一下一个基础多页应用的目录结构
├── node_modules # 项目依赖包目录
├── build # 项目 webpack 功能目录
├── config # 项目配置项文件夹
├── src # 前端资源目录
│ ├── images # 图片目录
│ ├── components # 公共组件目录
│ ├── pages # 页面目录
│ │ ├── page1 # page1 目录
│ │ │ ├── components # page1 组件目录
│ │ │ ├── router # page1 路由目录
│ │ │ ├── views # page1 页面目录
│ │ │ ├── page1.html # page1 html 模板
│ │ │ ├── page1.vue # page1 vue 配置文件
│ │ │ └── page1.js # page1 入口文件
│ │ ├── page2 # page2 目录
│ │ └── index # index 目录
│ ├── common # 公共方法目录
│ └── store # 状态管理 store 目录
├── .gitignore # git 忽略文件
├── .env # 全局环境配置文件
├── .env.dev # 开发环境配置文件
├── .postcssrc.js # postcss 配置文件
├── babel.config.js # babel 配置文件
├── package.json # 包管理文件
├── vue.config.js # CLI 配置文件
└── yarn.lock # yarn 依赖信息文件
vue-cli3构建多页面应用
创建一个项目hello-world
vue create hello-world cd hello-world npm run serve
在src目录下新建pages目录,在pages下新建页面
App.vue和main.js无用,可以删除,文件名对应着页面名
===index.js==========================================================================
import Vue from 'vue'
import App from './index.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
index.vue=====================================================================================
<template>
<div id="app">
<h1>page2</h1>
</div>
</template>
<script>
export default {
name: 'page2'
}
</script>
根目录下新建vue.config.js=======================================================================
let glob = require('glob')
//配置pages多页面获取当前文件夹下的html和js
function getEntry(globPath) {
let entries = {}, tmp, htmls = {};
// 读取src/pages/**/底下所有的html文件
glob.sync(globPath+'html').forEach(function(entry) {
tmp = entry.split('/').splice(-3);
htmls[tmp[1]] = entry
})// 读取src/pages/**/底下所有的js文件
glob.sync(globPath+'js').forEach(function(entry) {
tmp = entry.split('/').splice(-3);
entries[tmp[1]] = {
entry,
template: htmls[tmp[1]] ? htmls[tmp[1]] : 'index.html', // 当前目录没有有html则以共用的public/index.html作为模板
filename:tmp[1] + '.html' // 以文件夹名称.html作为访问地址
};
});
console.log(entries)
return entries;
}
let htmls = getEntry('./src/pages/**/*.');
module.exports = {
pages:htmls,
publicPath: './', // 解决打包之后静态文件路径404的问题
outputDir: 'output', // 打包后的文件夹名称,默认dist
devServer: {
open: true, // npm run serve 自动打开浏览器
index: '/page1.html' // 默认启动页面
}
}
访问页面
运行npm run serve就能访问啦
index页面:http://localhost:8080/ 或者http://localhost:8080/index.html (如果没有index文件夹)