小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前文我们学习使用了 Vue-Router 的子路由, 本文来学习 Vue-Router 的路由传参,
Vue-Router 路由传参
比如商品详情页面, 模板都一样的, 不过商品内容不一样, 这时候只需要定义一个路由, 通过传递不同的商品 id 即可实现由同一路由来展示不同的内容.
Vue-Router 路由传参
// src/router/index.js 路由定义模块
import Vue from 'vue'
import Router from 'vue-router'
// import PageOne from '@/components/PageOne.vue'
import PageTwo from '@/components/PageTwo.vue'
import NotFound from '@/components/NotFound.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
redirect: { name: 'PageOne' }, // 重定向到name为 PageOne 的路由
},
{
path: '/page-one',
name: 'PageOne',
component: One,
},
{
path: '/page-two/:id',
name: 'PageTwo',
component: Two,
props: true, // 这里定义 props 为true 允许路由接收参数
},
{
path: '**',
component: NotFound, // 404页面, 找不到上面的页面时, 使用`**`进行匹配, 都会转到notfound404页面
},
],
})
在路由定义好后, 我们在页面中进行访问 相应的 路由
// App.vue
由于要动态传入参数 id, 这里的 to 需要用 :to 表示是动态的值, 绑定路由的 name, 进行路由匹配.
<template>
<div id="app">
<!-- <router-link to="/page-one/one2">page-one/one2</router-link> -->
<router-link :to='{"name": "PageTwo", params:{a: 1, b: 2, c: 3, d: 4}}'
>动态路由- 路由传参</router-link
>
<router-view />
</div>
</template>
- page-two.vue
<template>
<div class="page-two">page-two</div>
</template>
<script>
export default {
name: 'PageTwo',
created() {
// 通过 this.$route 可以获取当前路由对象, 包含路由的相关属性参数
const paramsId = this.$route.params.id
console.log(paramsId)
},
}
</script>
- 路由改造后的 page-two.vue 可以通过
props传递参数
<template>
<div class="page-two">page-two</div>
</template>
<script>
export default {
name: 'PageTwo',
props: ["id"] // 这里的id为传递过来的
created() {
// 可以直接打通传递过来的数据
const paramsId = this.$route.params.id
console.log(paramsId)
}
}
</script>
路由传参小结一下
第一种 this.$route.params.id
第二种 props
第三种 <router-link :to={‘name’:名字, params{键值对...}}>
import axios from 'axios'
Vue.prototype.axios = axios
只要在入口文件里使用一次即可 其他组件用
this.$http.get
切换路由参数的时候,组件不会卸载
但是,切换路由组件的时候,组件会卸载