vue跳转到其他页面

简介: 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.{
   mathJaxContainer[0]}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()
相关文章
|
4天前
|
JavaScript 前端开发 安全
Vue响应式设计
【5月更文挑战第30天】Vue响应式设计
24 1
|
3天前
|
JavaScript 程序员 网络架构
vue路由从入门到进阶 --- 声明式导航详细教程
vue路由从入门到进阶 --- 声明式导航详细教程
vue路由从入门到进阶 --- 声明式导航详细教程
|
3天前
|
资源调度 JavaScript UED
vue路由的基础知识总结,vueRouter插件的安装与使用
vue路由的基础知识总结,vueRouter插件的安装与使用
|
3天前
|
JavaScript
|
4天前
|
编解码 JavaScript API
Vue在移动端的表现如何?
【5月更文挑战第30天】Vue在移动端的表现如何?
11 2
|
4天前
|
JavaScript 前端开发 API
Vue与其他框架的对比优势
【5月更文挑战第30天】Vue与其他框架的对比优势
11 1
|
4天前
|
JavaScript
Vue常用知识点总结
Vue常用知识点总结
12 0
|
5天前
|
JavaScript Java 测试技术
基于vue和微信小程序的校园自助打印系统+springboot+vue.js附带文章和源代码设计说明文档ppt
基于vue和微信小程序的校园自助打印系统+springboot+vue.js附带文章和源代码设计说明文档ppt
25 7
|
5天前
|
JSON JavaScript 前端开发
|
6天前
|
JavaScript 前端开发 Java
开发语言漫谈-Vue
Vue严格说来不是一门语言