vue.js路由的几种传参方式及特点,包括router-link,$router.push,动态路由匹配,params和query

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ForMyQianDuan/article/details/82798803

最近vue用的比较多,就想对各种知识做一个小结,比如这个就是路由导航的一个小总结。具体内容如下:

一、<router-link>
<router-link>标签中的to属性用来指定路由路径。
to的类型:string | Location。可以是字符串或者是个目标位置对象。
用法如下:
在这里插入图片描述
to的本质其实就是调用了编程式导航的router.push(…)方法。也就是说当你点击 时,router.push(…)会在内部调用,点击 等同于调用 router.push(…)。
在这里插入图片描述
二、编程式导航的router.push(location, onComplete?, onAbort?)
该方法的参数可以是一个字符串路径,或者一个描述地址的对象。例如:
在这里插入图片描述
但需要注意:path只能跟query共存,不能跟params共事。例子如下:
在这里插入图片描述

三、动态路由匹配
在做路由配置的时候需要这样写,如:id,:code ,/test/goods/:id/code/:code:

Vue.use(VueRouter);
let router = new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/test/goods/:id/code/:code",
      name: "goods",
      component: testGoods
    }]
})

一个“路径参数”使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 this.$route.params,可以在每个组件内使用。
在页面中,我们这样获取参数:

<template>
    <div>
        <h1>goods id: {{$route.params.id}},code:{{$route.params.code}}</h1>
        <h2>网址后面跟了跟路由参数个数匹配的参数,网页才会被正确显示,如:http://localhost:8888/test/goods/1001/Code/100001</h2>
        <h2>网址后面没有参数或参数数量不对,则网页不会显示,如:http://localhost:8888/test/goods/或http://localhost:8888/test/goods/1001/</h2>
    </div>
</template>

<script type="text/ecmascript-6">
export default {};
</script>

<style scoped lang="scss" rel="stylesheet/scss">
</style>

结果:
在这里插入图片描述
需要注意的事:采用params的方式的路由访问,网址比如带有完整的参数。如果参数数量不对或者没有参数,网页不会正确显示,如下图。
在这里插入图片描述

而用query的方式(注意看url的写法),即使没有参数网页一样会显示,只是读不出参数而已。

<h1>goods id: {{$route.query.id}},code:{{$route.query.code}}</h1>

在这里插入图片描述

对带参数的query(注意看url的写法),结果如下:
在这里插入图片描述

再看看匹配模式:
在这里插入图片描述

还有一些需要知识扩展的可以去官网看看。
我的参考资料:
https://router.vuejs.org/zh/api/#router-link
https://router.vuejs.org/zh/guide/essentials/navigation.html
https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html#响应路由参数的变化

猜你喜欢

转载自blog.csdn.net/ForMyQianDuan/article/details/82798803