前言
Vue-router笔记:路由的传参(两种方法)
一、使用动态路由
// 配置动态路由
path: '/路径:参数',
component: 组件
二、使用query
this.$router.push({
path: '/me',
query: {
name: 'Anna',
age: 17
}
})
三、使用步骤
1.配置路由
router/index.js代码如下:
// 配置路由相关的信息
import Vue from "vue";
import VueRouter from "vue-router";
// 懒加载
const Home = () => import('@/components/Home')
const About = () => import('@/components/About')
const User = () => import('@/components/User')
const Me = () => import('@/components/Me')
// 1.安装插件,通过Vue.use(插件)
Vue.use(VueRouter)
// 2.创建VueRouter对象
const routes = [
{
// 跟路由的重定向, 访问根路径重定向到/home
path: '/',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
// 配置动态路由
path: '/user:userId',
component: User
},
{
path: '/me',
component: Me
}
]
const router = new VueRouter({
// 配置路由和组件之间的映射关系
routes,
// mode默认为hash
mode: 'history',
linkActiveClass: 'active'
})
// 3.将router对象传入到Vue实例
export default router
2.传参
App.vue代码如下:
<template>
<div id="app">
<h2>App组件</h2>
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<h2>router-link传参跳转</h2>
<router-link :to="'/user' + userId">用户</router-link>
<router-link :to="{path: '/me', query: {name: 'Elsa', age: 18}}">我的</router-link>
<h2>button点击事件传参跳转</h2>
<button @click="userClick">用户</button>
<button @click="meClick">我的</button>
<!-- 显示router-link中路由的内容 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
userId: 'zhangsan'
}
},
methods: {
userClick() {
this.$router.push('/user' + this.userId)
},
meClick() {
this.$router.push({
path: '/me',
query: {
name: 'Anna',
age: 17
}
})
}
}
}
</script>
<style>
.active{
color: blue;
}
</style>
3.演示效果
总结
Vue-router笔记:路由的传参