vue-router 中路由动态传参与详情页UI渲染

我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。例如,我们有一个 User 组件,对于所有 ID 各不相同的用户,都要使用这个组件来渲染。那么,我们可以在 vue-router 的路由路径中使用“动态路径参数”来达到这个效果:

 

1. 编程式导航

[ User.vue ]:触发事件动态传参并跳转至相应路由

<li v-for="(item,index) in userList" :key="item.id" @click="showTable(item.id)">点击跳转至用户详情页</li>

showTable (id) {
   this.$router.push({ name: 'user', params: { id: id } })
}

[ router.js ]:

const router = new VueRouter({
  routes: [
    // 动态路径参数 以冒号开头
    { path: '/user/:id', 
name: 'user',
component: User
        //components: {
         // default: () => import('./components/User.vue')
        //},
     }
  ]
})

 

编程式导航传递参数有两种类型:字符串、对象

// 字符串
 this.$router.push('user')

// 对象 this.$router.push({ path: 'user' }) // 命名的路由,变成 /user/id/edward this.$router.push({ name: 'user', params: { id: 'edward' }}) // 带查询参数,变成 /user?id=edward this.$router.push({ path: 'user', query: { id: 'edward' }})

 

根据动态参数 id 展示详情UI:

点击跳转至相应的路由页面后,如果想要渲染UI界面,需要通过this.$route.params.id 或 this.$route.query.id 的方式获取参数,从而向后台请求相应的数据:

const { id } = this.$route.params
axios.get(`http://www.edward.com/detail?id=${id}`).then(res =>{
  this.name= res.name
this.age = res.age })

 

编程式导航时,如果连续几次触发路由导航,相当于在路由中添加了相同的路由会报错

"Navigating to current location ("/nav/form") is not allowed",

【解决方法】:在引用过vue-router的文件当中加上如下代码:

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const VueRouterPush = Router.prototype.push
Router.prototype.push function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

 

2. 声明式导航

[ User.vue ]:触发事件动态传参并跳转至相应路由

// 写法一:
<router-link tag="li" :to="{ path: `/user/${id}` }" v-for="(item,index) in userList" :key="index">点击跳转至用户详情页</router-link>
// 写法二:
<router-link tag="li" :to="{ name: 'user', params: { id: item.id } }" v-for="(item,index) in userList" :key="index">点击跳转至用户详情页</router-link>

// 写法三:查询路由方式
<router-link tag="li" :to="{ path: '/user', query: { id: item.id } }" v-for="(item,index) in userList" :key="index">点击跳转至用户详情页</router-link>

 

 1.命名路由搭配params,刷新页面参数会丢失

 2.查询参数搭配query,刷新页面数据不会丢失

 

[ router.js ]:(同上)

posted @ 2020-01-13 16:34  牧羊狼  阅读(2923)  评论(0编辑  收藏  举报