Vue单页应用开发中,路由跳转是最常见的操作之一。本文总结Vue Router提供的几种跳转方式,重点区分params和query传参的差异,并结合代码示例说明。
一、声明式导航:router-link
使用<router-link>标签可以直接在模板中跳转,它会渲染为<a>标签,但会阻止默认页面刷新。
- <!-- 直接跳转,不带参数 -->
- <router-link to="/testDemo">
- <button>点击跳转</button>
- </router-link>
- <!-- 带query参数,地址栏可见 -->
- <router-link :to="{path:'testDemo', query:{setid:123456}}">
- <button>点击跳转(query)</button>
- </router-link>
- <!-- 带params参数,地址栏不可见 -->
- <router-link :to="{name:'testDemo', params:{setid:1111222}}">
- <button>点击跳转(params)</button>
- </router-link>
复制代码
注意:使用params时必须配合name,不能只用path,否则params会被忽略。
二、编程式导航:this.$router.push()
在方法中通过$router.push()跳转更灵活,常用于按钮点击、登录验证等逻辑。
- <template>
- <div>
- <button @click="goTo">点击跳转</button>
- </div>
- </template>
- <script>
- export default {
- methods: {
- goTo() {
- // 直接跳转
- this.$router.push('/testDemo');
-
- // 带query参数(地址栏可见)
- this.$router.push({path:'/testDemo', query:{setid:123456}});
-
- // 带params参数(地址栏不可见)
- this.$router.push({name:'testDemo', params:{setid:111222}});
- }
- }
- }
- </script>
复制代码
三、params与query传参的对比
1. 请求方式类比:query传参类似HTTP GET请求,参数拼接在URL中,刷新页面后参数依然存在;params传参类似HTTP POST请求,参数不显示在URL中,但刷新页面时参数会丢失(除非在路由配置中动态路径)。
2. 地址栏表现:
- path + query:地址栏显示为 /testDemo?setid=123456
- name + params:地址栏显示为 /testDemo(参数不可见)
3. 接收参数:目标组件内通过 $route 对象获取(注意是$route,不是$router)。
- <template>
- <div>
- testDemo {{ this.$route.query.setid }}
- </div>
- </template>
复制代码 对应接收params的方式:this.$route.params.setid。
四、a标签跳转:只能跳转站外链接
- <a href="https://www.baidu.com"><button>跳转百度</button></a>
复制代码 直接使用<a>标签跳转外部链接没问题,但无法实现Vue路由内部跳转(会刷新页面)。如需内部跳转,仍然推荐router-link或$router.push。
五、前进/后退:this.$router.go()
- // 后退一步,等同 history.back()
- this.$router.go(-1);
- // 前进一步,等同 history.forward()
- this.$router.go(1);
复制代码
也可以在模板中绑定按钮:
- <button @click="goBack">上一页</button>
- <button @click="goForward">下一页</button>
- methods: {
- goBack() { this.$router.go(-1); },
- goForward() { this.$router.go(1); }
- }
复制代码
六、综合示例:一个包含多种跳转方式的页面
- <template>
- <div id="app">
- <router-link to="/">[跳转到主页]</router-link>
- <router-link to="/login">[登录]</router-link>
- <router-link to="/logout">[登出]</router-link>
-
- <button @click="goHome">[跳转到主页]</button>
- <button @click="goBack">[上一页]</button>
- <button @click="goForward">[下一页]</button>
- </div>
- </template>
- <script>
- export default {
- name: "App",
- methods: {
- goHome() {
- this.$router.push("/");
- },
- goBack() {
- this.$router.go(-1);
- },
- goForward() {
- this.$router.go(1);
- }
- }
- };
- </script>
复制代码
总结:
- 使用声明式导航(router-link)更语义化,适合静态链接。
- 编程式导航($router.push)适合逻辑跳转。
- 传参选query还是params取决于是否需要参数持久化:query刷新不丢失,params刷新丢失(除非使用动态路由)。
- 地址栏显示参数用query,隐藏参数用params。
- 前进后退用$router.go(n)。
掌握这些方式后,基本能满足Vue单页应用中的页面跳转需求。 |