<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo</title>
<style>
a{
text-decoration: none;
font-size: 14px;
background-color: #ddd;
color: blue;
padding: 5px;
padding-bottom: 0;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
a:not(:first-child){
margin-left: -5px;
}
a:hover{
color: darkblue;
}
#root div:last-child{
margin-top: 5px;
border: 1px solid #d3d3d3;
width: 200px;
height: 100px;
font-family: Arial, Helvetica, sans-serif;
}
.router-link-active {
color:darkblue;
background-color: #d3d3d3;
}
</style>
</head>
<body>
<div id="root">
<div>
<router-link to="/home">Home</router-link>
<router-link to="/users/foo">Foo</router-link>
<router-link to="/users/bar">Bar</router-link>
</div>
<router-view></router-view>
</div>
</body>
</html>
// index.js
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const Home = {
template:"<div>here is Home page</div>"
}
const User = {
template:"<div>here is User:{{$route.params.id}}</div>"
}
const router = new VueRouter({
routes:[
{
path:"/home",
component:Home
},
{
path:"/users/:id",
component:User
},
{
path:"/",
redirect:"/home"
}
]
})
const vm = new Vue({
router
}).$mount("#root")
从/foo
切到/bar
抑或 从/bar
切到/foo
,User组件
并没有经历重建,而是复用,这也是为了实现高效渲染。
但有以下两种方式来监听路由切换,
watch
const User = {
template:"<div>here is User:{{$route.params.id}}</div>",
watch:{
$route(to,from){
console.log("to:",to);
console.log("from",from);
}
}
}
beforeRouteUpdate
const User = {
template:"<div>here is User:{{$route.params.id}}</div>",
beforeRouteUpdate:function(to,from,next){
console.log("to",to);
console.log("from",from);
next();
}
}