Files
ClassContent/历届学生/吴欣阳/每天课程/2021-07-20/router.html
2024-09-27 02:06:13 +08:00

129 lines
3.6 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">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 组件来导航. -->
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/home">首页</router-link>
<router-link to="/about">关于我</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<div>
<router-view></router-view>
</div>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script>
// 0. 如果使用模块化机制编程导入Vue和VueRouter要调用 Vue.use(VueRouter)
// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Home = {
template: `<div>
<ul>
<li @click="enterInfo(item)" v-for="item in list">{{ item.title }}</li>
</ul>
</div>`,
data() {
return {
list: [
{ id: 1, title: '新闻1' },
{ id: 2, title: '新闻2' },
{ id: 3, title: '新闻3' },
]
}
},
methods: {
enterInfo(item) {
console.log(item);
this.$router.push({
name: 'info',
query: {
id: item.id
}
})
}
}
}
const About = { template: '<div>关于我</div>' }
const Info = {
template: `
<div>详情页 {{ $route.query.id }}</div>
` ,
created() {
console.log(this.$route.query);
},
beforeRouteLeave(to, from, next) {
var isLeave = confirm("你确定离开吗?")
if (isLeave) {
next()
}
}
}
// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About,
beforeEnter: (to, from, next) => {
console.log("别人正在打算访问about页面");
next()
}
},
{
path: '/info',
name: 'info',
component: Info,
},
]
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
})
router.beforeEach((to, from, next) => {
console.log("to: ", to);
console.log("from: ", from);
next()
})
// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
el: '#app',
router
})
</script>
</html>