一、rooter-link切换路由
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<!--切换路由链接-->
<a href="#/login">用户登录</a>
<a href="#/regist">用户注册</a>
<!--切换路由标签 router-link 标签必须加入to属性 to="路由路径"-->
<router-link to="/login">用户登录</router-link>
<router-link to="/regist">用户注册</router-link>
<!--切换路由标签【完整写法】-->
<router-link :to={path:'/login'}>用户登录</router-link>
<router-link :to={path:'/regist'}>用户注册</router-link>
<!--名称切换路由:根据路由对象名称切换路由显示不同的组件 根据路由名称切换路由只能使用router-link-->
<!--
【推荐使用命名路由】
-->
<router-link :to="{name:'Login'}">用户登录</router-link>
<router-link :to="{name:'Regist'}">用户注册</router-link>
<!--显示路由组件标签-->
<router-view></router-view>
</div>
</body>
</html>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!--路由cdn-->
<script src="https://unpkg.com/vue-router/dist/vue-router.js "></script>
<script>
const login = {
template: `<div><h3>用户登录</h3></div>`
};
const regist = {
template: `<div><h3>用户注册</h3></div>`
};
const router = new VueRouter({
routes: [
//name:这个属性代表路由对象的名称, 用来给路由对象一个唯一的名称标识
{path:'/login', component:login, name:'Login'},
{path: '/regist', component:regist, name: 'Regist'}
]
});
const app = new Vue({
el: "#app",
data:{},
methods:{},
components:{
login,
regist
},
router:router
});
</script>
二、在js代码中切换路由
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<router-link :to="{name:'Login'}">用户登录</router-link>
<router-link :to="{name:'Regist'}">用户注册</router-link>
<hr>
<!--通过js进行路由切换-->
<button v-on:click="login">用户登录</button>
<button v-on:click="regist">用户注册</button>
<router-view></router-view>
</div>
</body>
</html>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!--路由cdn-->
<script src="https://unpkg.com/vue-router/dist/vue-router.js "></script>
<script>
//登录组件
const login = {
template: `<div><h3>用户登录</h3></div>`
};
//注册组件
const regist = {
template: `<div><h3>用户注册</h3></div>`
}
const router = new VueRouter({
routes:[
{path:'/login', component:login, name:'Login'},
{path:'/regist', component:regist, name: 'Regist'}
]
});
const app = new Vue({
el: "#app",
data:{},
methods:{
login(){
//发送axios请求完成登录,想赢回来之后切换路由到主页
//this.$route object 当前路由对象
//this.$router vueRouter 代表路由管理对象
// this.$router.push('/login'); 不建议使用
// this.$router.push({path:'/login'}); 不建议使用
//因为如果已经是当前路由,再切换到当前路由前端控制台会报错,但是不影响程序运行,可以加判断解决
if(this.$route.name!='Login'){
this.$router.push({name:'Login'});//使用名称切换 , 建议使用
}
},
regist(){
if(this.$route.name!='Regist'){
this.$router.push({name: 'Regist'});
}
}
},
components:{
login,
regist
},
router:router
});
</script>