温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue router中参数传递的方式是什么

发布时间:2022-05-06 11:13:04 来源:亿速云 阅读:125 作者:iii 栏目:大数据

这篇文章主要介绍“vue router中参数传递的方式是什么”,在日常操作中,相信很多人在vue router中参数传递的方式是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”vue router中参数传递的方式是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

vue-router传递参数分为两大类

  • 编程式的导航 router.push

  • 声明式的导航 <router-link>

编程式的导航 router.push

编程式导航传递参数有两种类型:字符串、对象。

字符串

字符串的方式是直接将路由地址以字符串的方式来跳转,这种方式很简单但是不能传递参数:

this.$router.push("home");

对象

想要传递参数主要就是以对象的方式来写,分为两种方式:命名路由、查询参数,下面分别说明两种方式的用法和注意事项。

命名路由

命名路由的前提就是在注册路由的地方需要给路由命名如:

vue router中参数传递的方式是什么

命名路由传递参数需要使用params来传递,这里一定要注意使用params不是query。

目标页面接收传递参数时使用params

特别注意:命名路由这种方式传递的参数,如果在目标页面刷新是会出错的

使用方法如下:

this.$router.push({ name: 'news', params: { userId: 123 }})

代码如下:

<template>
 <div class="hello">
  <h2>{{ msg }}</h2>
  <button @click="routerTo">click here to news page</button>
 </div>
</template>

<script>
export default {
 name: 'HelloWorld',
 data () {
  return {
   msg: 'Welcome to Your Vue.js App'
  }
 },
 methods:{
  routerTo(){
   this.$router.push({ name: 'news', params: { userId: 123 }});
  }
 }
}
</script>

<style>
</style>接受传递的参数:<template>
 <div>
  this is the news page.the transform param is {{this.$route.params.userId}}
 </div>
</template>
<script>
</script>

运行效果如下:

vue router中参数传递的方式是什么

查询参数

查询参数其实就是在路由地址后面带上参数和传统的url参数一致的,传递参数使用query而且必须配合path来传递参数而不能用name,目标页面接收传递的参数使用query。

注意:和name配对的是params,和path配对的是query

使用方法如下:

this.$router.push({ path: '/news', query: { userId: 123 }});代码如下:<template>
 <div class="hello">
  <h2>{{ msg }}</h2>
  <button @click="routerTo">click here to news page</button>
 </div>
</template>

<script>
export default {
 name: 'HelloWorld',
 data () {
  return {
   msg: 'Welcome to Your Vue.js App'
  }
 },
 methods:{
  routerTo(){
   this.$router.push({ path: '/news', query: { userId: 123 }});
  }
 }
}
</script>

<style>
</style>接收参数如下:<template>
 <div>
  this is the news page.the transform param is {{this.$route.query.userId}}
 </div>
</template>
<script>
</script>

运行效果如下:

vue router中参数传递的方式是什么

声明式的导航

声明式的导航和编程式的一样,这里就不在过多介绍,给几个例子大家对照编程式理解,

例子如下:

字符串

<router-link to="news">click to news page</router-link>

命名路由

<router-link :to="{ name: 'news', params: { userId: 1111}}">click to news page</router-link>

运行效果如下:

vue router中参数传递的方式是什么

查询参数

<router-link :to="{ path: '/news', query: { userId: 1111}}">click to news page</router-link>

运行效果如下:

vue router中参数传递的方式是什么

到此,关于“vue router中参数传递的方式是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI