vue中路由的query参数

856 阅读1分钟

「这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战」。


在本篇的内容我会给大家介绍一下关于vue的路由传参的事情,在我们的路由中有两种传递参数方式分别是query参数和,在之前我们发Ajax请求时候也发送过query参数通过地址后面加问号的方式写 <router-link :to="/home/message/detail?id=666&title=你好">在多组数据中我们需要通过&符号进行参数分割。

<template>
	<div>
		<ul>
			<li v-for="m in messageList" :key="m.id">
				<!-- 跳转路由并携带query参数,to的字符串写法 -->
				<!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; -->
			
			</li>
		</ul>
		<hr>
		<router-view></router-view>
	</div>
</template>

<script>
	export default {
		name:'Message',
		data() {
			return {
				messageList:[
					{id:'001',title:'消息001'},
					{id:'002',title:'消息002'},
					{id:'003',title:'消息003'}
				]
			}
		},
	}
</script>

注意在我们写路由传参的时候通过url的方式传递参数需要对参数进行编码先是加上v-bind也就是:to这样才可以对里面的数据变成方法不只是字符串。里面需要的地方需要在加上${}

当然这种这种写法相对没有这么友好又叫加 又要加 ``的最后还要加上${}所以还有另外的一种写法也就对象的形式:path是想到那个位置至于参数就是通过query进行传递

        <router-link :to="{
                path:'/home/message/detail',
                query:{
                        id:m.id,
                        title:m.title
                }
        }">
                {{m.title}}
        </router-link>

接下来就是在组件中接收了,我们在之前也知道了route是可以获取组件挂载的路由参数而参加都是在query属性里面所以我们可以通过console.log(this.route是可以获取组件挂载的路由参数而参加都是在query属性里面所以我们可以通过`console.log(this.route)的方式查看是否成功,也可以使用{{$route.query.xx}}`直接解析在组件中。

<template>
	<ul>
		<li>消息编号:{{$route.query.id}}</li>
		<li>消息标题:{{$route.query.title}}</li>
	</ul>
</template>

<script>
	export default {
		name:'Detail',
		mounted() {
			console.log(this.$route)
		},
	}
</script>

总结路由的query参数

  1. 传递参数

    <!-- 跳转并携带query参数,to的字符串写法 -->
    <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
    				
    <!-- 跳转并携带query参数,to的对象写法 -->
    <router-link 
    	:to="{
    		path:'/home/message/detail',
    		query:{
    		   id:666,
                title:'你好'
    		}
    	}"
    >跳转</router-link>
    
  2. 接收参数:

    $route.query.id
    $route.query.title