Vue 路由get传值
1.动态传值
1.1需要在路由配置时指定参数: {component:'/home/:id'}
1.2在routerlink中指定格式:<router-link :to="'/home/'+123"></router-link>
1.3在跳转到的页面中通过this.$route.params获取指定的值
2.Get传值
2.1需要在路由配置时指定参数: {component:'/home'}
2.2在routerlink中指定格式:<router-link :to="'/home?aid='+123"></router-link>
2.3在跳转到的页面中通过this.$route.query获取指定的值
示例代码
import Vue from 'vue' import App from './App.vue' import Home from './components/Home.vue' import Detail from './components/Detail.vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [{ path: '/home', component: Home }, { path: '/detail/:id', component:Detail },{ path:'/detailget', component:Detail }, { path: '*', redirect: '/home' }] const router = new VueRouter({routes}); new Vue({ el: '#app', router, render: h => h(App) })
<template> <div id="home"> 我是Home <ul> <li v-for="(item,key) in list"> <router-link :to="'/detail/'+key">{{item}}</router-link> </li> </ul> <ul> <li v-for="(item,key) in list"> <router-link :to="'/detailget?id='+key">{{item}}</router-link> </li> </ul> </div> </template> <script> export default { data() { return { list: ["123", "456"] }; } }; </script>
<template> <div id="detail"></div> </template> <script> export default { mounted(){ console.log("动态穿过来的值是:"+this.$route.params.id); console.log("Get穿过来的值是"+this.$route.query.id) } } </script>