vue嵌套路由中params传递参数的示例分析

2023-05-17,,

这篇文章主要介绍vue嵌套路由中params传递参数的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

在嵌套路由中,父路由向子路由传值除了query外,还有params,params传值有两种情况,一种是值在url中显示,另外一种是值不显示在url中。

1、显示在url中

index.html

<div id="app"> 
  <!-- router-view 路由出口, 路由匹配到的组件将渲染在这里 --> 
  <router-view></router-view> 
  </div>

main.js params传值是通过 :[参数值] 如path: "/home/game/:num"

import Vue from 'vue' 
import VueRouter from 'vue-router' 
Vue.use(VueRouter) 
//引入两个组件 
import home from "./home.vue" 
import game from "./game.vue" 
//定义路由 
const routes = [ 
  { path: "/", redirect: "/home" },//重定向 
  { 
    path: "/home", component: home, 
    children: [ 
      { path: "/home/game/:num", component: game } 
    ] 
  } 
] 
//创建路由实例 
const router = new VueRouter({routes}) 
 
new Vue({ 
  el: '#app', 
  data: { 
    id:123, 
  }, 
  methods: { 
  }, 
  router 
})

home.vue 在home中具体的值就跟在路径后面,如 “/home/game/123”,也就是说传递给子路由的值就是 123

<template> 
  <div> 
    <h4>首页</h4> 
    <router-link to="/home/game/123"> 
      <button>显示</button> 
    </router-link> 
    <router-view></router-view> 
  </div> 
</template>

game.vue 在子路由中,通过 this.$route.params.参数名来接受传递过来的值

<template> 
  <h4>王者荣耀{{ this.$route.params.num }}</h4> 
  </template>

2、不显示在url中,如果在PC端将传递的值显示在url中,这样无形中就存在安全隐患,如果客户不小心修改了url那样就会出错,移动端就无所谓了,如何才能不显示在url中,同样很简单,但是需要给映射的路径起一个别名,通过name来取别名

同样只需将上面的main.js中的定义路由改为如下样子,在子路由中通过name来给路径其一个game1的别名。

//定义路由 
const routes = [ 
  { path: "/", redirect: "/home" },//重定向 
  { 
    path: "/home", component: home, 
    children: [ 
      { name: "game1", path: "/home/game/", component: game } 
    ] 
  } 
]

home.vue 中router-link修改为:to="{ name:'game1', params: {num: 123} }" params中是要传递的参数,这样传递的参数就不会显示在url中。

<template> 
  <div> 
    <h4>首页</h4> 
    <router-link :to="{ name:'game1', params: {num: 123} }"> 
      <button>显示</button> 
    </router-link> 
    <router-view></router-view> 
  </div> 
</template>

运行的结果如下图

以上是“vue嵌套路由中params传递参数的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注本站行业资讯频道!

《vue嵌套路由中params传递参数的示例分析.doc》

下载本文的Word格式文档,以方便收藏与打印。