1. 程式人生 > 其它 >路由鉤子&非同步請求axios

路由鉤子&非同步請求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/"
    }
  ]
}