Vue 通过 vue 的 router 传递参数两种方式总结

Vue: 通过 vue 的 router 传递参数两种方式总结

通过 vue 的 router 传递参数,通俗说法例如:通过id进行页面跳转并获取数据的方法总结

(一)命名路由传参,即使用params

形式如下:

this.$router.push({ name: 'editor', params: { id: 1 }})

这种方法的name是指路由中定义的那个name,而不是页面路径。跳转到的页面路由不会包含任何参数信息。刷新后就会丢失。

(二)查询传参

形式如下:

this.$router.push({ path: 'jotter/article', query: { id: 1 }});

结合超链接,即可实现点击标题或摘要传递参数到文章详情页面并跳转功能,只要在详情页面获取到该参数并向数据库发送请求即可。获取参数的形式如下

this.$route.query.id

用两种方法实现第二种方法

1、第一种方法

(1)第一步:配置路由:

在router文件夹得index.js配置路由

  {
          path: '/notices/detail/:id',
        //   redirect: {
        //     name: 'ProductIndex',
        // },
        name: 'Notice',
          // component: ProductIndex,
          component:() => import ('@/components/home/NoticeDetail'),
          meta: {
            requireAuth: true
          }
        },

(2)第二步:在Notice.vue页面写链接跳转实现跳转

完整链接跳转如下:

<ul class="notice-list-ul">
        
         <li
        v-for="notice in notices"
        :key="notice.id"
       
      >
     <router-link :to="'notices/detail/'+ notice.id">

          <i class="header-icon el-icon-info" >{{ notice.name }} </i>
       </router-link>
      </li>
      </ul>

下面得代码从上面摘取而来,只是用来说明重点

形式如下:

<router-link :to="'notices/detail/'+ notice.id">

          <i class="header-icon el-icon-info" >{{ notice.name }} </i>
       </router-link>

(3)第三步:跳转页面根据id获取数据

​ 1)获取id

 data() {
    return {    
  id:parseInt(this.$route.params.id), 
  notice: {},
    };
  },

​ 2)钩子函数

 mounted(){
    this.getNoticeDetail()
  },

​ 3)获取数据

methods:{
      getNoticeDetail(id){
          var _this = this
          var url = 'notices/detail/' + this.id
          this.$axios.get(url).then (resp => {
              if(resp && resp.status === 200){
                  _this.notice = resp.data
                  console.log(_this.notice )
              }
          })
      }
  }

2、第二种方法:

(1)配置路由:

  {
          path: '/teas/detail/',
        name: 'ProductIndex',
          component:() => import ('@/components/home/ProductIndex'),
          meta: {
            requireAuth: true
          }
        },

(2)第二步:在Product.vue页面写链接跳转实现跳转

链接跳转如下

  <router-link :to="{path:'/teas/detail',query:{id:tea.id}}">
                <div class="product-title">
                  <a href="">{{ tea.name }}</a>
                </div>

(3)第三步:跳转页面根据id获取数据

​ 1)钩子函数

   mounted(){
     this.loadOneProduct() 
  },

​ 2)获取数据

 loadOneProduct(){   
       var _this = this   
      var url = '/teas/detail/' + this.$route.query.id
      this.$axios.get(url).then(resp => {       
        if(resp && resp.status === 200){
          _this.products = resp.data;       
          console.log(_this.products)
        }
      })  
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值