Files
ClassContent/历届学生/逯帅帅/每日课程/2021-03-23/vue-router.html
2024-09-27 02:06:13 +08:00

166 lines
3.4 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.router-link-exact-active {
color: red;
}
</style>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 组件来导航. -->
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/index">首页</router-link>
<router-link to="/about">我的</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<div class="content">
<router-view></router-view>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="./vue-router.js"></script>
<script>
// 0. 如果使用模块化机制编程导入Vue和VueRouter要调用 Vue.use(VueRouter)
// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Index = {
template: `
<div>
<ul>
<router-link tag="li" :to="{ path: '/info', query: { id: item.id } }" v-for="item in newsList" >
{{item.title}}
</router-link>
</ul>
</div>
`,
data() {
return {
newsList: [
{ id: 1, title: '哈哈'},
{ id: 2, title: '哈哈'},
{ id: 3, title: '哈哈'},
]
}
},
methods: {
goInfo(id) {
this.$router.push({
path: '/info',
query: {
id: id
}
})
}
}
}
const About = {template: '<div>我的</div>'};
const Login = {
template: '<div @click="LoginSub">登录</div>',
methods: {
LoginSub() {
localStorage.setItem("token","W3456754567UIUYTFRDGFHNGRE7")
if (this.$route.query.hasOwnProperty("from")) {
this.$router.replace({
path: this.$route.query.from
})
}
}
}
};
const Info = () => {
return {
template: `
<div>
详情 {{ $route.query.id }}
</div>
`,
created() {
console.log(this.$route.query.id)
}
}
};
const routes = [
{
path: '/index',
component: Index,
meta: {
title: '首页',
isLogin: false
}
},
{
path: '/about',
component: About,
meta: {
title: '我的',
isLogin: true
}
},
{
path: '/login',
component: Login,
meta: {
title: '登录',
isLogin: false
}
},
{
path: '/info',
component: Info(),
name: 'info',
meta: {
title: '详情页',
isLogin: false
}
},
]
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
routes
});
router.beforeEach((to, from, next) => {
document.title = to.meta.title;
if (to.meta.isLogin) {
// 是否登录
if (localStorage.getItem("token") != null) {
next()
} else {
next({
path: '/login',
query: {
from: to.path
}
})
}
} else {
next()
}
})
// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
router,
el: '#app',
});
</script>
</html>