目前搭建好了VueRouter,肯定会涉及到页面 之间的跳转
- 基于超链接的方式,一旦地址发生变化,加载组件变化
- 基于脚本的方式来进行跳转,
一、通过标签跳转
Vue路由提供了一个新的组件,router-link
<router-link to="/register"></router-link>
在路由跳转的时候,router-link组件默认会解析为a标签,但是不建议直接用a标签,a标签有默认行为。如果你用的是router-link,底层已经对a做了处理。
跳转的时候,还可以指定路由的名字
-
<router-link :to="{name:'Register'}"></router-link>
Register就是路由配置里面name属性定义的值
-
const routes = [ { path:"/", redirect:"/login" }, { path: '/login', component: Login }, { path: '/register', name:"Register", component:()=>import("@/views/Register.vue") }, { path: '/home', component:Home } ]
二、脚本跳转
在js中想要实现页面跳转我们可以使用
-
window.location.href="/home"
这种跳转页面直接强制替换。
Vue中想要实现跳转,切换组件,并不是页面强制更新
在Vue中提出了一个$router对象,就是用于路由跳转的对象
-
methods:{ forwardHome(){ console.log(this); console.log(this.$router); this.$router.push("/home") } }
跳转的时候,$router代表的就是配置路由对象,里面包含了跳转的函数。
-
this.$router.push({name:"Home"})
name属性代表路由的名字。
常用的跳转函数:
push:记录你跳转的历史
replace:不会记录跳转的历史,登录后跳转到主页
扩展:go(-1)返回上一级
-
this.$router.go(-1)
扩展
router-link这个标签,身上还可以写如下的属性
属性名字 | |
---|---|
tag | 你如果想要让router-link渲染为其他标签 tag=“button” |
active-class | 激活这个连接的时候,动态添加一个class active-class=”active“ |
replace | 等同于 $router.replace() replace=”true” |
event | 可以设置以什么事件来触发,click event=”mouseover” |