07 vue之路由钩子与异步请求

九、路由钩子与异步请求

1.路由中的钩子函数

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

Profile.vue

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

image-20210326154259697

参数说明:

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

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

安装Axios

npm install axios -s

在Main.js中引用 Axios:

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

在static目录下新建一个目录mock,在里面创建data.json存放json数据**(假数据)**

制造假数据,另一种方式:第十章 Mock假数据

{
  "name": "Lisa",
  "password": 2021
}

在 beforeRouteEnter 中进行异步请求,案例代码如下:

Profile.vue

<script>
    export default {
        name: "UserProfile",
        props:['id'],
        beforeRouteEnter:(to,from,next)=>{
          console.log("进入路由之前");//加载数据
          next((vm)=>{
            vm.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>

测试:

image-20210326212833207

报错1:

 error  in ./src/views/Login.vue

Module build failed: Error: ENOENT: no such file or directory, scandir 'C:\Users\17316\Desktop\终级文档\1、笔记\1.20VUE\code\myCode\vue-elementui\node_modules\node-sass\vendor'

解决办法:

npm rebuild node-sass

报错2:node-sass报错:

卸载重装

// 卸载node-sass

npm uninstall node-sass

// 然后安装4.x版本(5.0之前)

npm install node-sass@4.14.1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值