路由跳转传参一共有两种
一种是通过组件名字传参另一种是通过路径传参
通过“组件名” 跳转到其他组件,使用params方式传参
组件A
<template>
<div>
<button @click="m1">跳转</button>
</div>
</template>
<script>
export default {
methods: {
m1() {
// 通过组件名跳转到其他组件,使用params方式传参
this.$router.push({ name: "luyouB", params: { a: "1", b: "2" } });
},
},
};
</script>
组件B
<template>
<div>
luyouB
<p>{{ c1 }}</p>
<p>{{ c2 }}</p>
</div>
</template>
<script>
export default {
data() {
return {
// params方式接收参数
c1: this.$route.params.a,
c2: this.$route.params.b,
// query方式接收参数
c3: this.$route.query.one,
c4: this.$route.query.two,
};
},
};
</script>
通过“组件路径”跳转到其他组件,使用query方式传参
组件A
<template>
<div>
<button @click="m2">跳转</button>
</div>
</template>
<script>
export default {
methods: {
m2() {
// 通过组件路径跳转到其他组件,使用query方式传参
this.$router.push({ path: "/luyouB", query: { one: "one", two: "two" } });
},
},
};
</script>
组件B
<template>
<div>
luyouB
<p>{{ c3 }}</p>
<p>{{ c4 }}</p>
</div>
</template>
<script>
export default {
data() {
// query方式接收参数
c3: this.$route.query.one,
c4: this.$route.query.two,
};
},
};
</script>
通过路由跳转携带id: path:"/home/:id" 或者 path: "/home:id"
query 和 params 的区别:
-
query 类似于get, 跳转页面之后, ur了参数后边会拼接参数, 类似: id=1; 非常重要性这样可以传下去
-
密码之类还是用params 刷新页面id 还是存在到但是 params 类似post 请求, 跳转页面之后, url不会拼接参数, 但是刷新页面id 会消失。
-
params传参,必须使用命名路由的方式传参;
-
params传参,不会显示在地址栏上,会保存在内存中,刷新会丢失,可以配合本地存储进行使用;
-
query的参数会显示在地址栏上,不会丢失;
路由跳转上级或下级
this.$router.go(1)
返回原来的页面
this.$router.go(-1)