路由钩子&异步请求axios

1.路由钩子

beforeRouterEnter

beforeRouterLeave

参数说明:

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

2.axios异步通信

npm install axios -s

npm install vue-axios -s

在main.js中导入,并安装

 

 Profile.vue

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

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

    }
</script>

<style scoped>

</style>

  static/mock/data.json

{
  "name": "狂神说java",
  "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/"
    }
  ]
}

  

 

posted @ 2021-06-16 17:03  GumpYan  阅读(101)  评论(0编辑  收藏  举报