前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vueRouter-编程式的导航 原

vueRouter-编程式的导航 原

作者头像
tianyawhl
发布2019-04-04 15:26:57
5910
发布2019-04-04 15:26:57
举报
文章被收录于专栏:前端之攻略

除了使用<router-link>创建a标签来定义导航链接,我们还可以借助router的实例方法,通过编写代码来实现。 router.push(location) 想要导航到不同的url,则使用router.push方法。这个方法会像history栈添加一个新的记录, 所以,当用户点击浏览器后退按钮时,则回到之前的url 当你点击<router-link>时,这个方法会在内部调用,所以说,点击<router-link :to="...">等同于调用 router.push(...) 该方法的参数可以是一个字符串路径,或者一个描述地址的对象,例如: //字符串 router.push("home") //对象 router.push({path:"home"}) 命名的路由 router.push({name:"user",params:{userId:123}}) //带查询参数,变成/register?plan=private router.push({path:'register',query:{plan:'private'}})

router.replace(location) 跟router.push很像,唯一不同就是,它不会像history添加新记录,而是跟它的方法名一样-替换掉当前的history记录 声明<router-link :to="..." replace>    编程式 router.replace(...)

router.go(n) 这个方法的参数是一个整数,意思是在history记录中向前或者后退多少步,类似window.history.go(n) 例子 //在浏览器记录中前进一步,等同于history.forward() router.go(1) //后退一步记录,等同于history.back() router.go(-1) //前进3步记录 router.go(3) //如果history记录不够用,那就默默的失败呗 router.go(-100) router.go(100)

一个简单的例子

代码语言:javascript
复制
<body class="">
    <script src="../js/vue.js"></script>
    <script src="../js/vue-router.js"></script>
    <div id="app">
        <button v-on:click="showHome">显示home</button>
        <button v-on:click="showOther">显示其他</button>
        <router-view></router-view>
    </div>
    <script>
    const Home = {
        template: `<div>this is the home page</div>`
    }
    const Other = {
        template: `<div>this is the other page</div>`
    }
    const router = new VueRouter({
        routes: [
            { path: "/home", component: Home },
            { path: "/other", component: Other },
        ]
    })

    var app = new Vue({
        el: "#app",
        router: router,
        methods: {
            showHome: function() {
                this.$router.push({ path: '/home' })
            },
            showOther: function() {
                this.$router.push({ path: '/other' })
            },
        }
    })
    //router.push({ path: '/home' }) 类似所有出现的/ 不能省略
    //this.$router.push({ path: '/home' }) 也可以写成router.push({ path: '/home' })
    </script>
</body>

(adsbygoogle = window.adsbygoogle || []).push({});

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/09/12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档