Vue路由复习

简单使用

Vue的路由是单页面应用。

vue-router4只能在vue3中使用。

vue-router3只能在vue2中使用。

npm install vue-router@3

引入插件:

import VueRouter from "vue-router"

使用插件:

Vue.use(VueRouter)

挂载:

router,需要挂载自定义的router

1、在src下新建router/index.js文件

2、相关代码如下:

//创建应用的路由器
import VueRouter from "vue-router";
import Test from "@/components/Test";
export default new VueRouter({
    routers:[
        {
            path:'/test',
            component:Test,
        },
    ]
})

3、在main.js中挂载router

import router from "router/index";
const vm = new Vue({
  render: h => h(App),
  store:store,
  router,
  beforeCreate(){
    Vue.prototype.$bus = this
  },
}).$mount('#app')

4、页面跳转

a标签替换为router-link    href替换为to

<router-link to="/Test" active-class="active">Test</router-link>

 页面渲染之后,就是a标签。

5、a标签的页面,往哪里放置呢,类似于插槽或者是iframe

<router-view></router-view>

注意点:

一般组件:

Banner.vue当作Header。 <Banner/>

路由组件:

不会出现<Test/>这样的组件使用,而是通过路由使用。

pages文件夹,一般放置路由组件。

不使用的路由组件,不是display:none,而是销毁了。

验证:

beforeDestroy() {
    console.log('Test组件即将被销毁')
}

打印一下VC,看看里边读了两个

$route:路由规则

        fullPath:'/test'

        hash:""

        matched:

        meta:

        name:

        params:{}

        path:'/test'

        query:{}

$router:整个应用只有一个。

整个应用的路由器,整个应用只有一个。

嵌套路由(多级路由)

export default new VueRouter({
    routers:[
        {
            path:'/test',
            component:Test,
            children:[
                {
                    path:'test2',
                    component:Test2,
                }
            ]
        },
    ]
})

里边的path,不用加/

<router-link class="list-group-item active-class="active" to="/home/news">news>

</router-link>

带参数

query参数:

<router-link to="/home/message/detail?id=666&title=你好"
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`"
<!-- :to,一旦加了冒号,双引号里边的内容就当作js去解析,发现写的是模板字符串,就可以解析混着的js变量了 ${m.id}和${m.title} -->

to的对象写法

<router-link :to="{
    path:'/home/message/detail',
    query:{
        id:m.id,
        title:m.title
    }
}"> 
{{m.title}}
</router-link>

路由页面:

mounted(){
    console.log(this.$route)
    /*
        fullPath:
        hash:
        matched:
        meta:
        name:
        params:
        path:
        query:{id:"666",title:"你好"}
    */
}

获取query参数:

<li>消息编号:{{$route.query.id}}</li>
<li>消息标题:{{$route.query.title}}</li>

params参数:

<router-link :to="/home/news/xaingqing/666/你好呀">xxx</router-link>
{
    name:'xiangqing',
    path:'/detail/:id/:title',
    componnent:Detail
}

使用占位符占据位置。

使用params携带参数:

{{$route.params.id}}

坑坑坑坑坑坑坑坑

如果使用的是params携带参数,那么则不允许使用path路径跳转,仅仅可以使用name属性。=

命名路由

就是定义路由的时候,起一个名字

export default new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About
        },
    ]
})

作用:利用name属性跳转。默认是路径。如果有多级路由的时候,那么name属性比较好用。

<router-link :to="{name:xiangqing}">xxxxx</router-link>

Props属性接收路由值

{
    name:'xiangqing',
    path:'detail/:id/:title',
    component:Detail,
//该对象中的所有key-value,都会以props的形式传递给Detail组件
    props:{
        a:1,
        b:'hello'
    }
    props:true  //若boolean值为真,就会只把params参数传递给Detail组件
    props($route){
        return {id:$route.query.id,title:'hello'};
    }
}

Detail.vue
props:['a','b']
props:['id','title']

路由历史记录

<router-link :replace="true">

默认是push的,可以前进后退。

替换router-link

shareProfit(){
      //跳转到一个组件,需要传递值
      this.$router.push({
        name:'share',
        params:{
         
        }
      });
    },
this.$router.forward();
this.$router.back();
this.$router //里边有个_proto_ 方法都在里边。
this.$router.go(1);
this.$router.go(-2);

路由缓存

路由切换的时候,组件默认是被销毁的。

<keep-alive include="组件name">
    <router-view />
</keey-alive>

<keep-alive :include="['News','Message']">

路由生命周期钩子

//激活
activated(){
    

},
//失活
deactivated(){


}

路由守卫

路由的权限。

前置路由守卫:

const router = new VueRouter({

})
//全局前置路由守卫【初始化和切换之前调用】
router.beforeEach((to,from,next )=>{
    next();//放行
})

export default router
const router = new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:'About',
            meta:{isAuth:false}
        }
    ]
})

if(to.meta.isAuth){
    next();//是否需要鉴权,鉴权成功
}

后置路由守卫:

router.afterEach((to,from)=>{
    document.title = to.meta.title || '哈哈哈哈系统'
})

document.title=$route.meta.title || '主页'

刷新的一瞬间,还是会出现问题,项目名为vue_test,package.json中有个name属性,index.html的title读取了这个属性。

独享路由守卫

children:[
    {
        name:'xinwen',
        path:'news',
        component:News,
        meta:{
            isAuth:true,
            title:'新闻'
        },
        beforeEnter:(to,from,next)=>{ //只有一个beforeEnter,没有afterEnter

        }
    }
]

 组件内路由守卫

//通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next){
    next();//还需要放行进入
},
//通过路由规则,离开该组件时被调用
beforeRouteLeave(to,from,next){
    next();//离开的时候也得放行
},

哈希模式

从#开始,到最后,都是hash值。

存在的意义:不会随着http请求,发送给服务器。

localhost:5000/students/#/fasldfjasdlfasdfasd,其接口地址

还是localhost:5000/students,但是服务器接收多了localhost:5000/students/

history模式

const router = new VueRouter({
    mode:'history',
    routes:[
        {},
    ]
})

默认开启的时hash模式。

开启了history模式,就没有了#了。

哈希和history的区别

1、哈希的浏览器兼容性好,history的兼容性略差。

2、项目上线问题。不与服务器发生交互没问题,一旦刷新页面,就会请求资源,如果后端接口没有这样的资源,就会报错。

3、后端需要匹配资源。【nodejs服务器 connect-history-api-fallback插件】

nodejs代码

const express = require('express');
const history= require('connect-history-api-fallback');
const app = express()
app.use(history())
app.use(express.static(_dirname+'/static'))

app.get('/person',(req,res)=>{
    res.send({
        name:'Tom',
        age:18
    })
})

app.listen(5005,(err)=>{
    if(!err) console.log('服务器启动成功了')
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值