html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Vue2 SPA</title>
<!-- CDN 引入 Vue, Vue Router, Vuex -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-router@3.5.4/dist/vue-router.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuex@3.6.2/dist/vuex.js"></script>
<style>
/* 简单的样式 */
.active { color: red; font-weight: bold; }
.sidebar { width: 200px; float: left; }
.content { margin-left: 210px; }
.tabs { padding: 5px; border-bottom: 1px solid #ccc; }
.tabs span { margin-right: 5px; cursor: pointer; }
</style>
</head>
<body>
<div id="app">
<!-- 根据当前路由显示内容 -->
<router-view></router-view>
</div>
<script>
// Vuex Store
const store = new Vuex.Store({
state: {
// 登录的用户会话
user: JSON.parse(localStorage.getItem('user')) || null,
// 菜单权限信息(由登录接口返回)
menus: [],
// 多标签页导航集合
tabs: []
},
mutations: {
setUser(state, payload) {
state.user = payload;
localStorage.setItem('user', JSON.stringify(payload));
},
setMenus(state, menus) {
state.menus = menus;
},
addTab(state, tab) {
// 防止重复添加
if (!state.tabs.find(item => item.path === tab.path)) {
state.tabs.push(tab);
}
},
removeTab(state, tabPath) {
state.tabs = state.tabs.filter(tab => tab.path !== tabPath);
},
resetTabs(state) {
state.tabs = [];
}
}
});
// 伪登录 API 模拟
function loginAPI(username, password) {
return new Promise((resolve, reject) => {
// 模拟网络延时
setTimeout(() => {
if (username === 'admin' && password === '123456') {
resolve({
username: 'admin',
// 预设菜单权限配置,菜单带有子菜单
menus: [
{ title: '首页', path: '/home' },
{
title: '管理',
path: '/manage',
children: [
{ title: '用户列表', path: '/manage/users' },
{ title: '角色列表', path: '/manage/roles' }
]
}
]
});
} else {
reject('用户名或密码错误');
}
}, 500);
});
}
// 登录组件
const Login = {
template: `<div>
<h2>登录</h2>
<form @submit.prevent="doLogin">
<div>
<label>用户名:</label>
<input v-model="username" />
</div>
<div>
<label>密码:</label>
<input type="password" v-model="password" />
</div>
<div>
<button type="submit">登录</button>
</div>
<div style="color:red;" v-if="errorMsg">{{ errorMsg }}</div>
</form>
</div>`,
data() {
return {
username: '',
password: '',
errorMsg: ''
};
},
methods: {
doLogin() {
loginAPI(this.username, this.password)
.then(data => {
store.commit('setUser', { username: data.username });
store.commit('setMenus', data.menus);
// 登录成功后跳转首页
this.$router.push('/home');
})
.catch(err => {
this.errorMsg = err;
});
}
}
};
// 主体布局组件:包含侧边栏菜单、多标签导航、内容区
const MainLayout = {
template: `<div>
<div class="sidebar">
<ul>
<template v-for="menu in menus">
<li>
<router-link :to="menu.path" active-class="active">{{ menu.title }}</router-link>
<ul v-if="menu.children">
<li v-for="child in menu.children">
<router-link :to="child.path" active-class="active">{{ child.title }}</router-link>
</li>
</ul>
</li>
</template>
</ul>
</div>
<div class="content">
<div class="tabs">
<!-- 多标签导航条 -->
<span
v-for="tab in tabs"
:key="tab.path"
@click="goTab(tab)"
:class="{active: tab.path === $route.path}">
{{ tab.title }}
<button @click.stop="closeTab(tab)">X</button>
</span>
</div>
<!-- 缓存内容区域 -->
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</div>`,
computed: {
menus() {
return store.state.menus;
},
tabs() {
return store.state.tabs;
}
},
watch: {
// 路由变化时添加标签
'$route'(to) {
store.commit('addTab', {path: to.path, title: to.meta.title || to.path});
}
},
methods: {
goTab(tab) {
this.$router.push(tab.path);
},
closeTab(tab) {
// 特殊情况:关闭当前页面,需跳转到其他页面
const isActive = tab.path === this.$route.path;
store.commit('removeTab', tab.path);
if (isActive) {
// 自动切换至最后一个标签
const lastTab = store.state.tabs[store.state.tabs.length - 1];
if (lastTab) {
this.$router.push(lastTab.path);
} else {
this.$router.push('/home');
}
}
}
},
created() {
// 初始加载入口页(假设登陆后默认跳转至 /home)
if (this.$route.path !== '/home') {
this.$router.push('/home');
}
}
};
// 示例详情页组件:列表→详情多开(使用路由参数区分)
const UserList = {
template: `<div>
<h3>用户列表</h3>
<ul>
<li v-for="user in users" :key="user.id">
<router-link :to="'/manage/users/' + user.id">{{ user.name }}</router-link>
</li>
</ul>
</div>`,
data() {
return {
users: [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' }
]
};
}
};
const UserDetail = {
template: `<div>
<h3>用户详情 - ID: {{ $route.params.id }}</h3>
<p>详情内容……</p>
</div>`
};
// 其他示例组件
const Home = {
template: `<div><h2>首页</h2><p>欢迎登录!</p></div>`
};
const RoleList = {
template: `<div><h3>角色列表</h3><p>角色管理内容……</p></div>`
};
// 路由配置:采用动态嵌套路由配置
const routes = [
{
path: '/login',
component: Login
},
{
path: '/',
component: MainLayout,
meta: { requiresAuth: true },
children: [
{
path: 'home',
component: Home,
meta: { title: '首页' }
},
{
path: 'manage',
component: { render: h => h('router-view') },
meta: { title: '管理' },
children: [
{
path: 'users',
component: UserList,
meta: { title: '用户列表' }
},
{
// 带有动态参数的详情页
path: 'users/:id',
component: UserDetail,
meta: { title: '用户详情' }
},
{
path: 'roles',
component: RoleList,
meta: { title: '角色列表' }
}
]
}
]
}
];
const router = new VueRouter({
mode: 'history', // 地址栏同步
routes
});
// 路由守卫:验证登录状态
router.beforeEach((to, from, next) => {
// 如果访问非登录页
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.state.user) {
return next('/login');
} else {
return next();
}
}
next();
});
// 全局操作:每日页面切换自动加入标签导航(在 MainLayout 中监控 $route 变化)
// 创建根实例
const app = new Vue({
el: '#app',
router,
store
});
</script>
</body>
</html>