项目:
使用vue create XXX创建项目,cli版本:@vue/cli 4.5.7
目录:
先放完整的项目目录
副页面的入口放在 src/subpage/ 下,可以不改原来main.js和App.vue的位置
多页面配置:
vue.config.js 文件 (主要)
参考vuecli官网配置 https://cli.vuejs.org/zh/config/#pages
module.exports = {
// cli4 配置多页面应用
pages: {
index: {
// page 的入口
entry: 'src/main.js',
// 模板来源
template: 'public/index.html',
// 在 dist/index.html 的输出
filename: 'index.html',
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: '主页面',
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ['chunk-vendors', 'chunk-common', 'index']
},
subpage: {
entry: 'src/subpage/main.js',
template: 'public/subpage.html',
filename: 'subpage.html',
title: '副页面',
}
}
}
其他文件跟原来的index.html、main.js、App.vue差不多,
subpage有自己的router,在router配置基路径:
base: 'subpage/',
新建public/subpage.html 文件
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
新建src/subpage/main.js 文件
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
Vue.config.productionTip = false;
new Vue({
router,
render: (h) => h(App),
}).$mount("#app");
新建src/subpage/App.vue 文件
<template>
<div id="app">
subpage
<div id="nav">
<router-link to="/aa">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</div>
</template>
<style lang="scss">
</style>
跳转
使用window.location.href = ‘/subpage’,或者a标签跳转
pc端和移动端跳转
在路由守卫中控制跳转
/**
* 判断是否为移动设备,是,则跳转到移动端的路径
*/
router.beforeEach((to, from, next) => {
if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
window.location.href = '/subpage/'
return
}
next()
})