面试题系列---【vue中router和route区别】

router和route区别:

1.router是路由对象,里边包含了很多属性和子对象,例如history对象,主要是用来进行路由跳转的

1.1路由跳转方式:

router-link

1.不带参数

// 字符串
<router-link to="apple"> to apple</router-link>
// 对象
<router-link :to="{path:'apple'}"> to apple</router-link>
// 命名路由
<router-link :to="{name: 'applename'}"> to apple</router-link>
// 注意:router-link中链接如果是'/'开始就是从根路由开始,如果开始不带'/',则从当前路由开始。

2.带参数

​ 2.1 ·query传递参数

//直接路由带查询参数query,地址栏变成 /apple?color=red
<router-link :to="{path: 'apple', query: {color: 'red' }}"> to apple</router-link>
// 命名路由带查询参数query,地址栏变成/apple?color=red
<router-link :to="{name: 'applename', query: {color: 'red' }}"> to apple</router-link>

​ 2.2 ·params传递参数

//直接路由带路由参数params,params 不生效,如果提供了 path,params 会被忽略
<router-link :to="{path: 'apple', params: { color: 'red' }}"> to apple</router-link>
// 命名路由带路由参数params,地址栏是/apple/red
<router-link :to="{name: 'applename', params: { color: 'red' }}"> to apple</router-link>

this.$router.push("/目标路由")

1.不带参数

// 字符串
router.push('apple')
// 对象
router.push({path:'apple'})
// 命名路由
router.push({name: 'applename'})

2.带参数

​ 2.1 ·query传递参数

//query传参,使用name跳转
this.$router.push({
    name:'second',
    query: {
        queryId:'20180822',
        queryName: 'query'
    }
})

//query传参,使用path跳转
this.$router.push({
    path:'second',
    query: {
        queryId:'20180822',
        queryName: 'query'
    }
})

//query传参接收
this.queryName = this.$route.query.queryName;
this.queryId = this.$route.query.queryId;

总结

query要用path来引入 ;

query在url中显示参数名和参数值

直白的来说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数

获取参数的不同`this.$route.query.xxx

​ 2.2 ·params传递参数

//params传参 使用name
this.$router.push({
  name:'second',
  params: {
    id:'20180822',
     name: 'query'
  }
})

//params接收参数
this.id = this.$route.params.id ;
this.name = this.$route.params.name ;

//路由
{
path: '/second/:id/:name',
name: 'second',
component: () => import('@/view/second')
}

总结:

使用params传参只能用name来引入路由, 如果写成path,接收参数页面会是undefined。

params是路由的一部分,必须要在路由后面添加参数名。

params相当于post请求,参数不会再地址栏中显示。

在浏览器url地址栏上展示的形式不同,params直接展示参数值。

获取参数的不同`this.$route.params.xxx

this.$router.replace("/目标路由")

与router.push(...)方法一致。

this.$router.go(n)

向前或者向后跳转n个页面,n可为正整数或负整数
vue 路由跳转四种方式 的区别

this.$router.push
跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面
this.$router.replace
跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)

this.$router.go(n)
向前或者向后跳转n个页面,n可为正整数或负整数

2.route表示当前的路由信息,用来获取路径内容。

原文地址:https://www.cnblogs.com/chenhaiyun/p/14901769.html