学习博客:【Vue】路由钩子与异步请求

两种路由模式

  • hash:路径带#
  • history:不带#
export default new VueRouter({
    
    
  mode: 'history',
  routes:[
  ]
});

404

<template>
  <div>
    <h1>404,页面不存在</h1>
  </div>
</template>

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

<style scoped>

</style>

导入组件

import NotFound from '../views/NotFound'

路由

{
    
    
  path: '*',
  component: NotFound
}

路由钩子与异步请求

beforeRouteEnter:进入路由前执行

beforeRouteLeave:离开路由前执行

  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. 安装axios

    cnpm install axios -s
    cnpm install --save vue-axios

  2. 导入组件

    import axios from 'axios';
    import VueAxios from 'vue-exios';
    
    Vue.use(VueAxios,axios)
    
  3. data.json

    {
          
          
      "name":"欢迎来到Vue",
      "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. 异步请求

    <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>
    

    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Aurinko324/article/details/125341668