第4章 **插件-路由传参(1.5)

e:\vue\myproject
components下新建/news文件夹用于本章测试

路由传参

https://segmentfault.com/a/1190000018711422?utm_source=tag-newest

  • 动态路由传参
  • params传参
  • query传参

1、动态路由匹配restful

动态路由传参,类似restful,在请求url里带参数
官网示例:
https://jsfiddle.net/yyx990803/4xfa2f19/
1、news/index.vue

  <template>
    <div>
      <p>新闻页</p>
      <ul>
      <li><router-link to="/newslist/123">美国新冠肺炎确诊病例升至50206例 死亡606例</router-link></li>
      <li><router-link to="/newslist/124">意大利新增确诊病例5249例 累计69176例</router-link></li>
      </ul>
      <router-view/>
    </div>
  </template>

  <script>
  </script>

  <style>
    ul{
      list-style: none;
    }
  </style>

2、创建路由组件news.vue

<template>
  <h1>这是新闻{{ $route.params.userId }}</h1>
</template>

  <script>
      export default {
        data() {
          return {

          };
        }
      }
    </script>

2、定义路由

import newsindex from '@/components/news/index'
import newslist from '@/components/news/newslist'

{
  path: '/news',
  name: 'news',
  component: newsindex
},
{
  path: '/newslist/:userId',
  name: 'newslist',
  component: newslist
}

测试一下

http://localhost:8080/#/news

可以将参数携带过去,后续可以根据id查询再显示新闻详情

2、路由命名和编程式的导航

这种方式需要为路由命名,然后再通过编程实现跳转
官网api:
命名路由:https://router.vuejs.org/zh/guide/essentials/named-routes.html
编程式的导航:https://router.vuejs.org/zh/guide/essentials/navigation.html

有两种方式

2.1通过params来传递参数##

** {name: , params} **
相当于路径参数/home/:id

step 1 :编写newslist2.vue

<template>
  <div>
   <h1>这是params新闻:{{ $route.params.id }}</h1>
   <h1>这是query新闻:{{ $route.query.id }}</h1>
   </div>
</template>

<script>
  export default{
    data(){
      return {}
    }
  }
</script>

step1 路由配置中必须有name属性 (如name: 'newslist2')

{
  path: '/newslist2',
  name: 'newslist2',
  component: newslist2
}

step2 news/index.vue中增加链接

              <li><router-link :to="{name:'newslist2',params:{id:45678}}">新闻params传参</router-link></li>

测试:

    http://localhost:8080/#/news

** 注意,编程时也可以通过事件触发 **
<router-link :to="{name:'home',params:{id:45678}}">跟代码调用 router.push() 是一回事:

router.push({ name: 'user', params: { id: 123 }})

2.2 通过query传参数

** name/query 或者 path/query **

相当于get请求方式,在url后面追加参数?userId=?&userName=......

关键代码


                <router-link :to="{path:'newslist2',query:{id:8907777}}">query2</router-link>

页面部分:

         <h1>这是query新闻:{{ $route.query.id }}</h1>

总结params与query异同

https://blog.csdn.net/unbreakablec/article/details/87159511

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容