vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue跳转到其他页面

vue如何跳转到其他页面

作者:左边的天堂

跳转到指定URL,向history栈添加一个新的纪录,点击后退会返回至上一个页面,这篇文章给大家介绍vue如何跳转到其他页面,包括无参跳转和带参跳转,本文结合实例代码给大家介绍的非常详细,需要的朋友参考下吧

一、无参跳转

跳转到指定URL,向history栈添加一个新的纪录,点击后退会返回至上一个页面。

// 声明式
<router-link :to = "…">
// 编程式,参数可以是一个字符串路径,或者一个描述地址的对象
<router.push('/user/index')>
// 直接写路由地址
this.$router.push('/user/index') 
// 地址对象
this.$router.push({path:'/user/index'})

二、带参跳转

1、query传参

this.$router.push({ path: '/user/index', query: { account: account }})

query传递的参数显示在地址栏中,刷新后依然存在,类似

http://localhost/user/index?account=123

参数接收方式

watch: {
   $route: {
     handler: function(route) {
       const account = route.query && route.query.account;
       console.info(account)
     },
     immediate: true
   }
}

或者放到created里面

created() {
   const {params, query} = this.$route;
   console.info(account)
}

或者放到mounted里面

mounted(){
   const account = this.$route.query && this.$route.query.account;
   console.info(account)
}

以上几种写法都是可以的。特别注意参数接收是使用$route,而非$router.

this.$router 相当于一个全局的路由器对象,包含了很多属性和对象(比如 history 对象),任何页面都可以调用其 push, replace, go 等方法。

this.$route 表示当前路由对象,每一个路由都会有一个 route 对象,是一个局部的对象,可以获取对应的 name, path, params, query 等属性。

2、params传参

this.$router.push({ name: 'User', params: { account: account }})

参数接收方式与第一种类似,参数是 params

watch: {
   $route: {
     handler: function(route) {
       const account = route.params && route.params.account;
   	   console.info(account)
     },
     immediate: true
   }
}

这种方式不会在uri后面追加参数,params传递刷新会无效;

三、替换当前页

替换history栈中最后一个记录

// 声明式
<reouter-link :to="..." replace></router-link>
// 编程式
this.$router.replace(...)

push方法也可以传replace,默认值:false

this.$router.push({path: '/homo', replace: true})

四、向前或向后跳转

this.$router.go(n)

与js原生的 window.history.go(n)用法相同, 向前或向后跳转 n 个页面,n 为正时前往下一个页面,为负时返回之前页面。也就是从history栈中取前面还是后面的某个页面。

this.$router.go(1)  // 类似 history.forward()
this.$router.go(-1) // 类似 history.back()

到此这篇关于vue如何跳转到其他页面的文章就介绍到这了,更多相关vue跳转到其他页面内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文