目录
一、准备
1、安装路由
npm i vue-router
2、在main.js文件中引入VueRouter 并应用插件
更新:
这个地方,可以在index.js中引入router并使用,然后在main.js中引入这个文件,可以实现同样效果。
import Vue from 'vue'
import App from './App.vue'
//引入VueRouter
import VueRouter from 'vue-router'
// 引入路由器
import router from './router/index'
//关闭vue的生产提示
Vue.config.productionTip = false
//应用插件
Vue.use(VueRouter)
new Vue({
render: h => h(App),
router:router
}).$mount('#app')
3、创建router文件夹,新建一个index.js文件,这个文件专门用于创建整个文件的路由器
二、基本使用
1、使用 router-link、router-view 实现路由跳转与显示,这个是最基本的使用
三、多级路由
1、index.js页面
2、home页面
四、三层路由嵌套
1、index.js页面
路由命名之后,在后续的跳转过程中不需要去写具体的地址,直接写name就可以了,后边的图片
有例子。
上
2、message页面
3、detail页面接收传递过来的参数:$route.params.XXX
五、不借助<router-link>
实现路由跳转,让路由跳转更加灵活
有的时候,通过一个名称来标识一个路由显得更方便一些,所以官方在路由中添加了一个name属性,命名这个属性之后我们访问这个属性就等于直接访问到路由;
普通:
//$router的两个API
this.$router.push({
path: '/user/:userId',
params:{
id:xxx,
title:xxx
}
})
this.$router.replace({
path: '/user/:userId',
params:{
id:xxx,
title:xxx
}
})
命名:
//$router的两个API
this.$router.push({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.replace({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //可前进也可后退
其实两者并没有什么区别,只是提供了两种方式来访问路由:
①通过路径匹配
②通过别名匹配