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记录。