vue如何通过点击事件实现页面跳转详解

vue如何通过点击事件实现页面跳转详解

目录

前言

this.$router.push()

this.$router.push()中的参数规则

参数的接收

注意

补充:VUE实现从一个页面跳转到另一个页面的指定位置

总结

前言

页面跳转,我们一般都通过路由跳转实现,通常情况下可直接使用router-link标签实现页面跳转,但是如果我们想通过点击别的标签实现页面跳转,怎么办呢?这个时候我们就要用到this.$router.push()方法,下面来给大家简单介绍一下使用!

this.$router.push()

1.首先我们要定义一个点击事件

2.在定义事件中调用this.$router.push()方法

<template> <button @click = "handle">点击跳转</button> </template> <script> export default{ methods:{ handle (){ // 路径/home对应我在router目录下index.js中定义的path属性值 this.$router.push('/home'); } } } </script>

目标跳转页面路由在router目录下index.js定义如下:

export default new Router({ routes: [ { path: '/home', name:'Home', component: Home, }, ] }) this.$router.push()中的参数规则

参数为字符串,即路径名称

// 路径/home对应router目录下index.js中定义的path属性值 this.$router.push('/home');

参数为对象

// 对应router目录下index.js中定义的path this.$router.push({path:'/home'});

参数为路由命名

// 对应router目录下index.js中定义的name this.$router.push({name:'Home'});

带传递参数

// params里面放置的是我们要传递过去的参数 this.$router.push({name:'Home',params:{user:'david'}});

带查询参数

// 带查询参数,传递过去的内容会自动拼接变成/home?user=david this.$router.push({path:'/home',query:{user:'david'}}); 参数的接收

当我们使用params进行传参时,只需在接收参数的地方使用this.$route.params进行接收即可

eg:

//传参 this.$router.push({name:'Home',params:{user:'david'}}); // 在name为Home的组件中接收参数 const id=this.$route.params.id; console.log(this.$route.params);//打印结果为{user:'david'}

当我们使用query传参时,只需在接收参数的地方使用this.$route.query进行接收即可,用法同上

!!!这里有一个小细节:$符号后面跟的是route不是router,跳转的时候 $后面跟的是router!!!

注意

query传参的参数会带在url后边展示在地址栏(/home?user=david),params传参的参数不会展示到地址栏

由于动态路由也是传递params的,所以在 this.$router.push() 方法中path不能和params一起使用,否则params将无效,需要用name来指定页面

我们也可以用this.$router.replace()来实现页面跳转,二者的区别是push跳转之后可以通过浏览器的回退键回到原来的页面,而一旦使用replace跳转之后,无法回到原来页面

补充:VUE实现从一个页面跳转到另一个页面的指定位置

例如,从网站的首页点击跳转到指定页面的底部。

首页 home

<div @click="toPath('/targetPage#target')"> <p>点击跳转</p> </div> methods:{ //点击跳转方法 toPath(path) { this.$router.push({path: path}) } }

跳转到的页面 targetPage

<div class="location" id="target"> <p>指定位置</p> </div> //在mounted里 mounted() { var hash = window.location.hash; var index = hash.lastIndexOf("#"); if (index != -1) { var id = hash.substring(index + 1, hash.length + 1); var div = document.getElementById(id); if (div) { setTimeout(function () { console.log($(div).offset().top); $('html, body').animate({scrollTop: $(div).offset().top - 43}, 500) }, 500); } } }

亲测有效 :D

总结

到此这篇关于vue如何通过点击事件实现页面跳转的文章就介绍到这了,更多相关vue点击事件实现页面跳转内容请搜索易知道(ezd.cc)以前的文章或继续浏览下面的相关文章希望大家以后多多支持易知道(ezd.cc)!

推荐阅读