Spring Boot与Vue中路由参数传递详解

2 下载量 94 浏览量 更新于2024-08-30 1 收藏 52KB PDF 举报
本文主要介绍了在Spring Boot和Vue.js中如何实现路由传递参数的方法,包括路径变量和查询参数两种方式。 在Spring Boot中,我们通常使用`@RestController`注解来创建一个RESTful的控制器。在`RouterController`类中,`@RequestMapping`用于指定请求的URL模板和HTTP方法。在方法`router`中,`@PathVariable`用于获取URL路径中的参数,例如`name`和`classid`,而`@RequestParam`则用于获取查询参数,如`type`和`num`。`@RequestParam`还可以设置默认值和是否必需。 示例代码如下: ```java package com.tang.demo1.controller; import org.springframework.web.bind.annotation.*; @RestController public class RouterController { @RequestMapping(path = {"/router/{name}/{classid}"}, method = RequestMethod.GET) public String router( @PathVariable("name") String name, @PathVariable("classid") int classid, @RequestParam(value = "type", defaultValue = "news") String type, @RequestParam(value = "num", required = false) int num) { // 访问http://localhost:8080/router/tang/101?type=spor&num=12 return name + classid + type + num; } } ``` 在Vue.js中,路由参数的传递主要是通过Vue Router进行。配置路由时,我们可以定义动态路径参数,这些参数以冒号`:`开头,如`id`和`type`。如果参数是可选的,可以在末尾添加问号`?`。 Vue Router配置如下: ```javascript const routes = [ { path: '/', name: 'HomePage', component: HomePage }, { path: '/user/:id?/:type?', name: 'User', component: User } ]; ``` 在Vue组件中,我们可以使用`props`来接收这些参数,或者通过`this.$route.params`来访问它们。例如,在`User`组件中: ```html <template> <div> <p>user</p> <router-link :to="'/user/' + item.id + '/' + item.type"> <!-- ... --> </router-link> </div> </template> <script> export default { props: ['id', 'type'], // 通过props接收参数 data() { return { // ... }; }, created() { console.log(this.$route.params); // 在组件生命周期钩子中访问参数 } }; </script> ``` 总结来说,Spring Boot通过`@PathVariable`和`@RequestParam`处理路径变量和查询参数,而Vue.js则通过Vue Router的动态路径参数和组件的`props`来实现类似的功能。在实际开发中,根据具体需求选择合适的方式传递和接收参数,可以提高应用的灵活性和可维护性。