在路由時(shí)傳遞參數(shù),一般有兩種形式,一種是拼接在url地址中,另一種是查詢參數(shù)。如:http://localhost:8080/router/tang/101?type=spor&num=12。下面根據(jù)代碼看一下,VUE 和 Spring Boot 中各自是如何處理傳遞和接受參數(shù)的。
Spring Bootpackage 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 = falsef) int num){ // 訪問(wèn) http://localhost:8080/router/tang/101?type=spor&num=12 return name + classid + type + num; } } 在url路徑中的,被稱為pathVariable,查詢參數(shù)被稱為pequestParm。在controller中接受參數(shù),可以直接在方法里用了。VUEroutes: [ { path: '/', name: 'HomePage', component: HomePage }, { path: '/user/:id?/:type?', name: 'User', component: User } ] 首先在路由中配置url中需要傳遞的參數(shù),被稱為動(dòng)態(tài)路徑參數(shù)。以“:”開(kāi)始,末尾的“?”表示為可選的參數(shù)。
<template> <div> <p>user</p> <router-link :to="'/user/' + item.id + '/' + item.type +'?name=' + item.type" :key="index" v-for="(item, index) in userList">{{item.name}}</router-link> <div v-if="childName"> <p>-----</p> {{childName}} </div> </div> </template> <script> var list = [ {'name': 'xiaoming', 'id': 123, 'type': 'vip'}, {'name': 'gangzi', 'id': 456, 'type': 'common'} ] export default { data(){ return { userList: list, childName: null } }, watch: { $route(){ if(this.$route.params.id){ this.childName = this.$route.params.id +'//////' + this.$route.query.name; }else{ this.childName = null } } }, methods: { }, created() { // this.$route.params為動(dòng)態(tài)路徑參數(shù) if(this.$route.params.id){ // this.$route.params為查詢參數(shù) this.childName = this.$route.params.id +'//////' + this.$route.query.name; }else{ this.childName = null } }, deactivated() { console.log('deact') }, computed: { }, components: { } }; </script> vue中接受參數(shù)需要從routes實(shí)例中獲取,動(dòng)態(tài)路徑參數(shù)在params里,查詢參數(shù)在query里。
當(dāng)vue的動(dòng)態(tài)路徑組件處在激活狀態(tài)時(shí),如果改變動(dòng)態(tài)路徑參數(shù),那么寫(xiě)在created()的方法將不會(huì)再次被調(diào)用,因?yàn)樵摻M件已經(jīng)創(chuàng)建好了。此時(shí),可以為$route添加一個(gè)watch,當(dāng)其發(fā)生變化時(shí),再獲取數(shù)據(jù)。
在路由時(shí)傳遞參數(shù),一般有兩種形式,一種是拼接在url地址中,另一種是查詢參數(shù)。如:http://localhost:8080/router/tang/101?type=spor&num=12。下面根據(jù)代碼看一下,VUE 和 Spring Boot 中各自是如何處理傳遞和接受參數(shù)的。
新聞熱點(diǎn)
疑難解答
圖片精選