404和路由钩子

一、路由模式与404

1.1、路由模式有两种:

  • hash:路径带#符号,如http://localhost/#/login
  • history:路径不带#符号,如http://localhost/login

修改路由配置,代码如下:
在这里插入图片描述
效果:
在这里插入图片描述

1.2、处理404创建一个名为NotFound.vue的视图组件:

<template>
    <h1>404,你的页面走丢了</h1>
</template>

<script>
    export default {
        name: "NotFound"
    }
</script>

<style scoped>

</style>

修改路由配置:

import NotFound from '../views/NotFound'
{
	path:'*',
	component: NotFound
}

效果:
在这里插入图片描述

二、路由钩子与异步请求

beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行

沿用上一篇博客“参数传递及重定向”项目!

修改Profile.vue:

<template>
    <div>
      <h1>个人信息</h1>
      {{id}}
    </div>
</template>

<script>
    export default {
        props: ['id'],
        name: "UserProfile",
        beforeRouteEnter:(to,from,next) => {
          console.log("进入路由之前");
          next();
        },
        beforeRouteLeave:(to,from,next) => {
          console.log("离开路由之前");
          next();
        }
    }
</script>

<style scoped>

</style>

效果:
在这里插入图片描述
参数说明:

  • to:路由将要跳转的路径信息
  • from:路径跳转前的路径信息
  • next: 路由的控制参数
  • next() 跳入下一个页面
  • next(‘/path’) 改变路由的跳转方向,使其跳到另一个路由
  • next(false) 返回原来的页面
  • next((vm)=>{}) 仅在beforeRouteEnter 中可用,vm是组件实例

在钩子函数中使用异步请求

1、安装Axios cnpm install axios -s
在这里插入图片描述

2、main.js引用Axios
在这里插入图片描述
3、在上述基础上,增加功能,实现在进入Profile.vue之前,完成数据的加载

新建static/mock/data.json:

{
  "name":"马西莫",
  "url": "http://baidu.com",
  "page": "1",
  "isNonProfit":"true",
  "address": {
    "street": "和平街道",
    "city":"湖南湘潭",
    "country": "中国"
  },
  "links": [
    {
      "name": "B站",
      "url": "https://www.bilibili.com/"
    },
    {
      "name": "4399",
      "url": "https://www.4399.com/"
    },
    {
      "name": "百度",
      "url": "https://www.baidu.com/"
    }
  ]
}

4、修改Profile.vue:

<template>
    <div>
      <h1>个人信息</h1>
      {{id}}
    </div>
</template>

<script>
    export default {
        props: ['id'],
        name: "UserProfile",
        beforeRouteEnter:(to,from,next) => {
          console.log("进入路由之前");//加载数据
          next(vm => {
            vm.getData();//进入路由之前执行getData;
          });
        },
        beforeRouteLeave:(to,from,next) => {
          console.log("离开路由之前");
          next();
        },
      methods: {
          getData: function () {
            this.axios({
              method: 'get',
              url: 'http://localhost:8080/static/mock/data.json'
            }).then(function (response) {
                console.log(response)
            })
          }
      }
    }
</script>

<style scoped>

</style>

运行效果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值