Vue入门十二、路由的跳转

路由之间的跳转有再种:
1、通过标签<router-link to='/login'>去登录</router-link>实现跳转
2、通过js实现:
this.$router.push({path:'/buy'})
this.$router.replace({path:'/buy'})
2.1push与replace的区别
push会向history插入新记录
replace不会插入history历史记录,如果返回上一页,则会跳转到上上一页中。上一页是不存在的
返回上一页面:this.$router.go(-1)

```
<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>

<script type="text/javascript" src="vue.js"></script>
<script type="text/javascript" src="vue-router.js"></script>
<script type="text/javascript">
    var Login={
        template:`
            <div>去登录去吧</div>
        `
    }
    var Register={
        template:`
            <div>去注册去吧</div>
        `
    }
    var Buy={
        template:`
            <div>去买东西</div>
        `
    }
    // 安装插件
    Vue.use(VueRouter);
    // 创建路由对象
    var router = new VueRouter({
        // 配置路由对象
        routes: [
            {path:'/login', name:'login', component:Login},
            {path:'/register', name:'register', component: Register},
            {path:'/buy', name:'buy', component: Buy}
        ]
    })
    new Vue({
        el:'#app',
        router,
        template:`
            <div>
                <router-link to='/login'>去登录</router-link>
                |
                <router-link to='/register'>去注册</router-link>
                <div>
                    <button @click="gogo">点我买东西</button>
                    <button @click="back">返回上一页</button>

</div>
<router-view></router-view>
</div>
`,
methods:{
gogo(){
// 有历史记录跳转
// this.$router.push({path:'/buy'})
// 没有历史记录跳转
this.$router.replace({path:'/buy'})
},
back(){
// 返回上一页
this.$router.go(-1)
}
}
})
</script>

</body>
</html>

猜你喜欢

转载自blog.51cto.com/12012821/2406228
0条评论
添加一条新回复