<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue@2.6.1.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue-router-3.01.js"></script>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 组件来导航. -->
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
<script>
// 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)
// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Foo = {
template: `
<transition name="slide">
<div class="foo">foo</div>
</transition>
`
}
const login = {
template: `
<transition name="fade">
<div class="bar">请先登录</div>
</transition>
`
}
const Bar = {
template: `
<transition name="fade">
<div class="bar">bar</div>
</transition>
`
}
// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
{
path: '/foo',
component: Foo,
},
{
path: '/',
component: Foo,
},
{
path: '/bar',
component: Bar,
},
{
path: '/login',
component: login,
},
];
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
// mode: 'history',
routes // (缩写) 相当于 routes: routes
})
router.beforeEach((to, from, next) => {
// 如果有token 说明该用户已登陆
if (localStorage.getItem('token')) {
// 在已登陆的情况下访问登陆页会重定向到首页
if (to.path === '/login') {
next({path: '/'})
} else {
next({path: to.path || '/'})
}
} else {
// 没有登陆则访问任何页面都重定向到登陆页
if (to.path === '/login') {
next()
} else {
next(`/login?redirect=${to.path}`)
}
}
})
// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
router
}).$mount('#app')
// 现在,应用已经启动了!
</script>
</body>
</html>
网友回复