Vue-router笔记:路由的传参

本文详细介绍了Vue-router的两种传参方法:动态路由和query参数。通过配置路由、使用$router.push进行传参,并展示了在App组件中如何实现按钮点击事件传参跳转的效果。最后给出了实际操作的代码示例。
摘要由CSDN通过智能技术生成


前言

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笔记:路由的传参

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值