第一种:声明式导航
router-link(必须要有to属性),可以实现路由的跳转
第二种:编程式导航
利用的是组件实例的$router.push|replace方法,可以实现路由的跳转
编程式导航优于声明式导航,编程式导航在跳转之前可以先处理一些业务
在控制台输入命令来安装所需的包
npm i vue-router@3 --save
注意:我们需要安装的是3.x.x版本,vue2已经不支持最新的vue-router了
编写简单的页面作为展示
路由组件如下:
在src下新建pages用于保存路由组件,在pages文件下新建两个文件夹分别命名为:hello、world
hello的组件样式为:
hello:发起
账号:
密码:
world的组件样式为:
world:接收
展示账号:
展示密码:
在src下新键router文件夹用于管理路由,在该文件夹下创建index.js文件
// 引入
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 配置路由
export default new VueRouter({
// 配置路由
routes: [
{
path: '/',
redirect: '/hello'
// component: () => import('../pages/hello/hello-index.vue')
},
{
path: '/hello',
component: () => import('../pages/hello/hello-index.vue')
},
{
// path: '/world/:keyword?'
path: '/world/:keyword',
component: () => import('../pages/world/world-index.vue')
}
]
})
在入口文件需要引入
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
import router from '../src/router'
new Vue({
render: (h) => h(App),
router
}).$mount('#app')
参数
1、params参数——属于路径中的一部分,但在我们配置路由的时候需要占位
2、query参数——不属于路径中的一部分,(/index?k=v) 不需要占位
写法
// 修改hello文件的点击函数:
methods: {
toWorld() {
this.$router.push('/world/' + this.text + '?password=' + this.password)
}
}
在world接收:
<template>
<div>
world:接收<br />
展示账号:<span>{{ $route.params.keyword }}span>
<br />
展示密码:<span>{{ $route.query.password }}span>
div>
template>
点击跳转之后,world就会接收参数进行使用
// 修改hello的跳转方式:
methods: {
toWorld() {
this.$router.push(`/world/${this.text}?password=${this.password}`)
}
}
// 1、需要在router/index.js文件里面给需要跳转的路由命名:
{
path: '/world/:keyword?',
component: () => import('../pages/world/world-index.vue'),
name:'world'
}
// 修改hello的跳转方式:
methods: {
toWorld() {
this.$router.push({
name: 'world',
params: {
keyword: this.text
},
query: {
password: this.password
}
})
}
}
会发现,一直点击的话会有报错,是因为vue-router来设计的时候采用了promise ,所以我们
需要增加成功和失败的回调就可以解决:
this.$router.push({
name: 'world',
params: {
keyword: this.text
},
query: {
password: this.password
}
},()=>{},()=>{})