vue-router参数传递

  1. 什么是传递参数呢?
    从一个组件传递到另一个界面的过程之中,是需要我们传递一些参数的,最开始渲染的肯定是App.vue, 首页被渲染,从app.vue,往用户组件里面一些东西。
  2. 准备工作:
    第一步:创建新的组件profile.vue
    profile => 配置动态路由
  3. 传递参数主要有两种类型:
    配置路由的格式: /router/:id
    传递的方式:在path后面跟上对应的值
    传递后形成的路径: router/123, /router/abc
  4. query的类型:
    配置路由的格式:/router,也就是普通配置
    传递的方式:对象中使用query的key作为传递的方式
    传递后形成的路径: /router?id=123, /router?id=abc

传递方式一演示:在path后面跟上对应的值

// 利用vue-router进行参数传递一:
import Vue from 'vue';
import Router from 'vue-router'

// 路由懒加载 => 优化首屏时间
const Home = () => import("../components/Home.vue");
const HomeNews = () => import("../components/HomeNews.vue");
const HomeMessage = () => import("../components/HomeMessage.vue");
const Profile = () => import("../components/Profile.vue");
const About = () => import("../components/About.vue");
const User = () => import("../components/User.vue")

// 1. Vue.use() 安装插件
Vue.use(Router);
// 2. 创建VueRouter对象
const routes = [
    {
      path: '',
      redirect: '/home'
    },
    {
      path: '/home',
      component: Home,
      children: [
        {
          path: '',
          redirect: 'news'
        },
        {
          path: 'news',
          component: HomeNews
        },
        {
          path: 'message',
          component: HomeMessage
        }
      ] 
    },
    {
      path: '/about',
      component: About
    },
    {
      path: '/user/:userId',
      component: User
    },
    {
      path: '/profile',
      component: Profile
    }
],

const router = new Router({
  // 配置路由和组件的映射关系
  routes
})

//3. 将router对象挂载到main.js
export default router

App.vue

<template>
  <div id="home">
     <router-link :to="/user'/' + useId"></router-link>
     <router-link :to="{ 
       path: '/profile', query: {name: 'why', age: 18, height: 1.88}
     }"></router-link>
     <router-view></router-view>
  </div>
</template>
export default {
   name: 'App',
   data() {
      return {
         userId: "LiuMing"
      }
   }
}

User.vue

<template>
  <div id='user'>
    <h2>我是用户界面</h2>
    <p>我是用户界面相关信息</p>
    <h2>{{userId}}</h2>
    <h1>{{$route.params.userId}}</h1>     
  </div>
</template>

<script>
  export default {
    name: 'User',
    computed: {
      userId() { 
         return this.$route.params.userId;
      }
    }
  }
</script>

Profile.vue

<template>
  <h2>我是一个profile组件</h2>
  <h2>{$route.query}</h2>
  <h2>{$route.query.name}</h2>
  <h2>{$route.query.age}</h2>
  <h2>{$route.query.height}</h2>
</template>

<script>
  export default {
    name: 'Profile'
  }
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值