Vue中router-view實現路由內容的地方。router-view可以看做是一個容器,它所渲染的組件是使用vue-router指定。router-view在哪裏引入組件就會在哪裏顯示。
路由跳轉的三種方式
一、router-link
語法:<router-link to=“跳轉頁面的路徑”>
在編譯之後,<router-link>會被渲染爲<a>標籤,to會被渲染爲href
<router-link to="home"></router-link>
在src/router/index.js文件中引入要跳轉的路徑:
export default new Router({
routes: [
...
{
path:'/home',
name:'home',
component: () => import('@/view/home/home.vue')
}
]
})
二、this.$router.push({path:’/home’})
login.vue
<template>
<div id="login">
<h1>歡迎登錄</h1>
賬號:<input type='text' placeholder="" v-model="username"> </br>
密碼:<input type="password" placeholder="" v-model="password"> </br>
<Button type="primary" @click="login" >登錄</Button>
</div>
</template>
<script>
export default {
name: 'login' ,
data(){
return{
username:'',
password:'',
};
},
methods:{
login(){
if(!this.username){
this.username='請輸入用戶名';
return;
}
if(!this.password){
this.password='';
return;
}
...
else{
this.$router.push({
path:'/home',
})
}
}
}
}
</script>
<style>
</style>
home.vue
<template>
<div id="home">
<span font-size=20px>登錄成功</span>
</div>
</template>
<script>
export default {
name: 'home'
}
</Script>
同樣在src/router/index.js文件中引入要跳轉的路徑,效果會成功跳轉到home所在的視圖中
三、this.$router.replace{path:’/’}同第二種方法
區別在於this.$router.push()會跳轉到不同的url,並且會想history棧中添加一個記錄,點擊後退會返回到上一個頁面。
this.$router.replace()不會向history中添加新記錄,但會替換掉當前的history記錄。