飞道的博客

Vue--自定义404页面 & 路由钩子路由钩子与异步请求

457人阅读  评论(0)

1. Vue--404和路由钩子

项目结构


路由模式有两种

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

1.1 使用hash路由模式(推荐)

修改路由配置,代码如下:

export default new Router({
   
  mode: 'history',
  routes: [
  ]
});

1.2 自定义置404页面


1.2.1 创建一个NotFound.vue视图组件

NotFound.vue

<template>
  <div>
    <img src="../../static/img/404.jpg" alt="">
  </div>
</template>

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

<style scoped>
</style>

1.2.2 配置路由

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

1.2.3 运行结果


1.3 路由钩子与异步请求

2个常用的与路由相关的钩子函数

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

1.3.1 路由钩子

Profile.vue

  export default {
   
    props: ['id'],
    name: "userProfile",
    beforeRouteEnter: (to, from, next) => {
   
      console.log("准备进入个人信息页");
      next();
    },
    beforeRouteLeave: (to, from, next) => {
   
      console.log("准备离开个人信息页");
      next();
    }
  }

参数说明:

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

1.3.2 异步请求

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

1.3.2.1 安装 Axios

当前项目目录打开命令行输入:

npm install --save axios vue-axios

1.3.2.2 main.js引用 Axios

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

1.3.2.3 准备数据

只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下。

{
   
  "name": "码云",
  "url": "https://gitee.com/",
  "page": 1,
  "isNonProfit": true,
  "address": {
   
    "street": "大渡口",
    "city": "重庆",
    "country": "中国"
  },
  "links": [
    {
   
      "name": "Axios中文文档",
      "url": "http://www.axios-js.com/zh-cn/docs/"
    },
    {
   
      "name": "百度",
      "url": "https://www.baidu.com/"
    }
  ]
}

1.3.2.4 beforeRouteEnter 中进行异步请求

<script>
  export default {
    
    //第二种取值方式
    props:['id'],
    name: "userProfile",
    //钩子函数 过滤器
    beforeRouteEnter: (to, from, next) => {
    
      //加载数据
      console.log("进入路由之前")
      next(vm => {
    
        //进入路由之前执行getData方法
        vm.getData()
      });
    },
    beforeRouteLeave: (to, from, next) => {
    
      console.log("离开路由之前")
      next();
    },
    //axios
    methods: {
    
      getData: function () {
    
        this.axios({
    
          method: 'get',
          url: 'http://localhost:8080/static/mock/data.json'
        }).then(function (response) {
    
          console.log(response)
        })
      }
    }
  }
</script>

1.3.2.5 路由钩子和axios结合结果




转载:https://blog.csdn.net/I_r_o_n_M_a_n/article/details/117172450
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场