URL传参
路由配置
文件结构
动态路由匹配
一个“路径参数”使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 this.$route.params,可以在每个组件内使用。
test1 跳转至 test2
test1.vue
<template>
<div>
<h1>test1</h1>
<router-link :to="'/test/test2/'+id">go test2</router-link>
<button @click="go()">go test2</button>
</div>
</template>
<script>
export default {
data() {
return {
id: 106
}
},
methods: {
go(){
this.$router.push({ path: `/test/test2/${this.id}` })
}
},
}
</script>
test2.vue
<template>
<div><h1>test2</h1>
<h2>ID:{{ this.$route.params.id }}</h2></div>
</template>
<script>
export default {
data() {
return {
id: this.$route.params.id
}
},
mounted() {
this.log()
},
methods: {
log(){
console.log(this.id);
}
},
}
</script>
带查询参数的URL传参
test3 跳转至 test4
test3.vue
<template>
<div>
<h1>test3</h1>
<router-link :to="{path: '/test/test4', query: {id: user.id, class: user.class }}">go test4</router-link>
<button @click="go()">go test4</button>
</div>
</template>
<script>
export default {
data() {
return {
user: {
id:106,
class: 102
}
}
},
methods: {
go(){
this.$router.push({path: '/test/test4', query: {id: this.user.id, class: this.user.class }})
}
},
}
</script>
test4.vue
<template>
<div>
<h1>test4</h1>
<h2>ID:{{ this.$route.query.id }}</h2>
<h2>Class:{{ this.$route.query.class }}</h2>
<h3><pre>{{ user }}</pre></h3>
</div>
</template>
<script>
export default {
data() {
return {
user: {
id: this.$route.query.id,
class: this.$route.query.class
}
}
},
mounted() {
this.log()
},
methods: {
log(){
console.log(this.user);
}
},
}
</script>
传参是this.$router,接收参数是this.$route
1.$router为VueRouter实例,想要导航到不同URL,则使用$router.push方法
2.$route为当前router跳转对象,里面可以获取name、path、query、params等