import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const Home = {
template:`
<div>
<h2>Home</h2>
<p>this is Home -{{$route.query.a}}</p>
</div>
`
}
const Parent = {
template:`
<div>
<h2>Parent</h2>
<p>this is Parent</p>
</div>
`
}
const Page404 = { /*404页面默认跳转,定义时不能以数字开头*/
template:`
<div>
<h2>404</h2>
<p>error:404 页面走丢了</p>
</div>
`,
beforeRouteEnter:(to,from,next)=>{
console.log(to);
console.log(from);
next()
},
beforeRouteLeave:(to,from,next)=>{
console.log(to);
console.log(from);
next()
}
}
const router = new VueRouter({
mode:'history',
data(){
return{
aaa:'fade'
}
},
base: __dirname,
routes:[
{path:'/',component:Home},
{path:'/Parent',component:Parent,
beforeEnter:(to,from,next)=>{
// console.log(to);
// console.log(from);
/* 第一种: 允许执行 next() 不允许next(false)*/
next()
}
},
{path:'*',component:Page404}
]
})
new Vue({
router,
template:`
<div id="app">
<h1>this is transition</h1>
<button @click="back">后退</button>
<button @click="returnhome">Home</button>
<button @click="go">前进</button>
<button @click="query">query</button>
<ul>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/Parent">/Parent</router-link></li>
<li><router-link to="/asdf">/错误的路由链接,跳转至404页面</router-link></li>
</ul>
<transition :name="aaa" mode="out-in">
<router-view></router-view>
</transition>
</div>
`,
watch:{
'$route' (to,from){
if(from.path == '/Parent'){
this.aaa = 'fade1';
}else{
this.aaa = 'fade2';
}
}
},
methods:{
back:function() {
router.go(-1);
},
go:function() {
router.go(1);
},
returnhome:function() {
router.push("/");
},
query:function() {
router.push({path:'/',query:{a:1,b:2}});
},
}
}).$mount('#app')
结果:
vue路由知识到此结束,以上所有案例均来自wos老师的教学视频,借此机会将自己所学到的分享给大家,非常感谢wos老师对vue小白的支持 qwq…