vue-router
在的应用都流行SPA应用(single page application)
传统的项目大多数用的是多页结构,当进行页面跳转的时候,会受到网络和性能的影响,用户体验不好
而单页面应用(SPA)就是用户通过操作地址栏来切换对应的组件(卸载和安装),无刷新切换,用户体验良好,Vue会使用官方提供的vue-router插件来使用单页面
安装插件:yarn add vue-router or cnpm install vue-router -S
![spa](https://i-blog.csdnimg.cn/blog_migrate/2997a6eac31c7ff21a4e91d993a38d93.png)
简单路由的实现
//引用路由
import Vue from 'vue';
import Router from 'vue-router';
//使用
Vue.use(Router);
let routes = [
{
path:"/cinema",
component:()=>import("@/views/cinema") //懒加载的方式
// component:resolve=>require(["@/views/cinema"],resolve) es5写法,如果用的话,都用一种写法
}
]
//实例化
let router = new Router({
mode:"hash", //默认是hash,还有history
routes
})
export default router
最后还需要将router让每个组件都可以访问到
import Vue from 'vue'
import App from './App.vue'
//引入router实例
import router from './router'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router //为了让每个组件都可以访问到路由的api($router/$route)
}).$mount('#app')
router-view
利用router-view来指定路由切换的位置
只能指定该组件子级的组件切换,如果子级下面还有子级的话,那就需要在子级中在设置一个
声明式导航router-link、编程式导航
<router-link
v-for = "title in titleLis"
:key = "title.id"
:to = "title.path"
active-class="active"
tag="li"
replace
>{{title.title}}</router-link>
<!--replace可以控制router-link的跳转不被记录
to指的是跳转的地址 key值是唯一的,必须加 tag是更改标签名-->
methods: {
toDetail(){ 上面直接@click="toDetail"
//方式二: 通过编程时导航方式实现路由跳转
this.$router.push("/detail/1") 还有back、forward、replace等等
}
}
小拓展:
vscode的对于vue组件的代码提示片段:
"Print to vue": {
"prefix": "vue",
"body": [
"<template>",
" <div>",
" ",
" </div>",
"</template>",
"",
"<script>",
"export default {",
" data () {",
" return {",
" ",
" }",
" },",
" methods: {",
" ",
" }",
"}",
"</script>",
"",
"<style lang=\"scss\" scoped>",
"",
"</style>",
""
],
"description": "快速创建vue单文件组件"
}
路由懒加载
vue只有在这个组件需要被渲染的时候才会去加载,且会把结果缓存起来工未来重新渲染(无需另加载)
懒加载也叫延迟加载,即在需要的时候进行加载,随用随载。如果在单页面中不用懒加载的话,那么运行webpack打包好的文件将会非常大,从而造成进入首页后就会进行大量数据的加载,延时过长,从而导致用户体验极差,而运用懒加载,会给首页分担加载的负担,减少加载用时
在第一次进入每个页面的时候都会进行一次加载,而过后就会将每个网页的结果缓存起来,下一次在访问的话就不用重新加载
{
path: '/about',
name: 'about',
component: () => import('@/views/About') //采用了路由懒加载方式
}
多级路由、默认路由和重定向
在创建路由表的时候,可以为每一个路由对象创建children属性,值为数组,在这个里面又可以配置一些路由对象来使用多级路由,注意:一级路由path前加’/’,而二级路由有两种写法如下:
let routes = [
{
path:"/films",
component:()=>import("@/views/films"),
children:[ //添加二级路由的同时,父级的vue文件也需要加上router-view
{
path:'/films/nowplaying', //第一种写法
component:()=>import("@/views/films/nowplaying")
},
{
name:"readyplaying",
path:'readyplaying', //第二种写法,一定不能加/
component:()=>import("@/views/films/readyplaying")
},
{
path:"", //默认进入该页面后就进入该子页面
redirect:"/films/nowplaying",
}
]
}
]
命名路由
路由对象配置name属性,在跳转的时候直接写name:main就会快速的找到此name属性对应的路由,不需要写大量的urlpath路径
<router-link
v-for="nav in navs"
:key="nav.id"
:to="{name:nav.name}"
>
{{nav.title}}</router-link>
{path:"guonei",component:Guonei,name:"guonei"},
{path:"guoji",component:Guoji,name:"guoji"}
动态路由匹配
name:"detail",
path:'/detail/:ids',
component:()=>import("@/views/detail"),
props:true //在路由自身可以通过props接受id参数去使用
在路由自己中可以通过props接收id参数去使用了
props:[‘id’]
也可以直接在详情页如下写法:
<p>详情页面 --> {{ids}} --> {{$route.params.ids}}</p>
路由模式
路由模式有两种:hash、history
hash模式和history模式的区别:
hash模式:较丑、支持IE8以上
history模式:优雅、支持IE10以上(h5新增)、需要后端配合将所有的访问都指向index.html,否则用户刷新页面会导致404错误
路由守卫
全局路由守卫(导航守卫、路由钩子、路由生命周期钩子)
beforeEach vs afterEach
//全局的前置路由守卫,路由跳转之前就会执行
router.beforeEach((to,from,next)=>{
if(from.path === "/center"){
console.log("从个人中心来的...")
}
next() //必须要执行的
})
//全局的后置路由守卫,路由跳转之后就回执行
router.afterEach((to,from,next)=>{
if(to.path === "/center"){
console.log("进去了个人中心")
}
})
局部路由守卫 beforeEnter
beforeEnter
beforeEnter:(to,from,next)=>{
console.log("进去到了个人中心...")
next() //若不放行则进不去个人中心页面
}
局部到组件内部的路由钩子
beforeRouteEnter beforeRouteLeave beforeRouteUpdate
beforeRouteEnter(to,from,next){
console.log("beforeRouteEnter......center",this)
next() //渲染该组件组件的对应(此)路由是被确认前调用的
//不写的话,进不去页面
//不能获取组件实例的this,因为在该实例执行前,组件实例还没被创建
},
beforeRouteLeave(to,from,next){
console.log("beforeRouterLeave......center",this)
//导航离开该组件的时候调用,可以访问到组件实例的this
}
//在页面跳转中用的
beforeRouteUpdate(to,from,next){
console.log("beforeRouteUpdate......center",this)
next() //只有在两个页面之间跳转才会执行
//可以访问到this
}
小拓展
正常你的js文件在notework上显示的是序号,这样的话可以将你的文件需要更该为你想要的名字
{
path:'/center',
component:()=>import(/* webpackChunkName: "cinema" */"@/views/center"), //将该名字更改(系统自动解析)
}
r o u t e r 和 router和 router和route的区别
$router是一个VueRouter的实例 可以导航到不同的路由里
r
o
u
t
e
是
route是
route是router跳转到的当前一个对象,里面包含该对象的path、query、name 、params
用法 :
this.$router.push() 跳转到指定的url 会向history栈添加一个记录 点击后退会返回上一页面
1、this.
r
o
u
t
e
r
.
p
u
s
h
(
p
a
t
h
:
′
/
d
e
t
a
i
l
′
,
q
u
e
r
y
:
)
t
h
i
s
.
router.push({path:'/detail',query:{}}) this.
router.push(path:′/detail′,query:)this.router.push(’/detail’)
使用当前的query: this.$route.query
2、this.$router.push({name:‘detail’,params:{}}) //name运用的是命名路由
使用当前的params this.$route.params
this.$router.replace() 跳转到指定的url 不会向history栈添加一个记录,点击返回不会回到上一次的历史地方
this.$router.go(n) 向前或向后跳转多少个页面(类似于 window.history.go())