<!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>
<style>
* {
margin: 0px;
padding: 0px;
list-style: none;
}
a {
text-decoration: none;
}
.router-link-active {
background: lime;
color: white;
}
ul {
overflow: hidden;
}
li {
margin-right: 10px;
float: left;
}
</style>
</head>
<body>
<div id="app">
<ul>
<li>
<router-link to="/index">首页</router-link>
</li>
<li>
<router-link to="/type">分类</router-link>
</li>
<li>
<router-link to="/shoppingcart">购物车</router-link>
</li>
<li>
<router-link to="/mine">我的</router-link>
</li>
</ul>
<router-view></router-view>
</div>
<template id="index">
<p @click="back">这是首页页面</p>
</template>
<template id="type">
<div>
<p><br>这是分类页面</p><br>
<ul>
<li>
<router-link to="/book">书本</router-link>
</li>
<li>
<router-link to="/clothes">衣服</router-link>
</li>
<li>
<router-link to="/drink">饮料</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</template>
<template id="book">
<p>这是书本页面</p>
</template>
<template id="clothes">
<p>这是衣服页面</p>
</template>
<template id="drink">
<p>这是饮料页面</p>
</template>
<template id="shoppingcart">
<p>这是购物车页面</p>
</template>
<template id="mine">
<div>
<p><br>这是我的页面</p>
<button @click="back">返回上一次访问的页面</button>
<button @click="toBook">跳转到书本页面</button>
<button @click="toIndex">跳转到首页</button>
</div>
</template>
<script src="../js/vue.js"></script>
<script src="../js/vue-router.js"></script>
<script>
var index = {
template: '#index',
methods: {
back() {
// 跳转到上一次访问的页面
this.$router.go(-1);
}
}
}
var type = {
template: '#type'
}
var book = {
template: '#book'
}
var clothes = {
template: '#clothes'
}
var drink = {
template: '#drink'
}
var shoppingcart = {
template: '#shoppingcart'
}
var mine = {
template: '#mine',
methods: {
back() {
// 跳转到上一次访问的页面
this.$router.go(-1);
},
toBook() {
this.$router.push('/book');
},
toIndex() {
this.$router.replace('/index');
}
}
}
var router = new VueRouter({
routes: [
{
path: '/index',
component: index
},
{
path: '/type',
component: type,
// children里面配置嵌套的子路由
children: [
{
path: '/book',
component: book
},
{
path: '/clothes',
component: clothes
},
{
path: '/drink',
component: drink
}
]
},
{
path: '/shoppingcart',
component: shoppingcart
},
{
path: '/mine',
component: mine
},
// 子路由也可以配置在第一层路径下,此时点击子路由,子路由相应的内容会渲染到第一层router-view里面
// {
// path: '/book',
// component: book
// },
// {
// path: '/clothes',
// component: clothes
// },
// {
// path: '/drink',
// component: drink
// },
{
path: '/*',
redirect: '/index'
}
]
})
new Vue({
el: '#app',
router,
})
</script>
</div>
</body>
</html>
1.this.$router.go(n);
n为正数时,跳转到当前路径后第n个路径
n为负数时,跳转到当前路径前第n个路径
2.this.$router.replace('/指定路径');
跳转到指定路径,替换掉histroy栈中最后一个记录,此时点击后退会跳转到上上层页面
3.this.$router.push('/指定路径');
跳转到指定路径,向history栈中添加一个新纪录,此时点击退后会跳转到上层页面