vue-router 动态路由

上一篇文章我们已经配置好了路由,下面,来说说如何实现动态路由。

比如,我想在 news 页点击列表项,跳转到对应项,如图所示: 

这里引用的数据是豆瓣电影,地址:

http://api.douban.com/v2/movie/in_theaters

eg:当我点击第一项时,跳转地址为 : http://localhost:8080/#/content/26752088

第二项时,跳转地址为:http://localhost:8080/#/content/26925317

也就是 content/id 这里的id是不同的

实现方式有两种:

第一种:

<ul>
  <li v-for="item in list">
    <router-link :to="'/content/'+item.id">{{item.title}}</router-link>
  </li>
</ul>

动态绑定 to 属性,传入 id,这里的 id 是 json 数据返回的

路由中需要这样写:

import Content from "./components/Content.vue" // 注册组件
// 路由配置
const routes = [
  {path: '/home', component: Home},
  {path: '/news', component: News},
  {path: '/content/:id', component: Content},
  {path: '*', redirect: '/home'}   /*默认跳转路由*/
]

注意:content 项的 path 需要以 :xxx 的形式定义.

我们可以在 content 组件中 使用 生命周期函数 获取到 id 值

// content 组件中
mounted() {
   console.log(this.$route.params)  // 获取动态路由传值
}

 实现效果:

第二种: get 方式传值

与第一种实现方式不同,但可以达到同样的效果,

当然,我们还是需要先引入组件

import Pcontent from "./components/Pcontent.vue"

我们先来看路由上的配置

const routes = [
  {path: '/home', component: Home},
  {path: '/news', component: News},
  {path: '/content/:aid', component: Content},
  {path: '/pcontent', component: Pcontent},  // 与正常注入一样
  {path: '*', redirect: '/home'}   /*默认跳转路由*/
]
<ul>
  <li v-for="(item,key) in list">
     <router-link :to="'/pcontent?id='+item.id">{{item.title}}</router-link>
  </li>
</ul>

这里 to 属性同样需要动态绑定 与第一种区别在于 路径名称后面,是以 ? 自定义名称 = xxx 来定义的

获取 id 值

 mounted() {
   console.log(this.$route.query);
 }

实现效果:

原文地址:https://www.cnblogs.com/Sky-Ice/p/9293402.html