Vue路由钩子

Vue路由钩子

beforeRouteEnter(to,from,next)这个就是其中一个路由钩子,相当于是拦截器,to是相当于request,from相当于是response,next就是跳转的意思。通常可以使用next(vm=>{xxx})来获取vm方法里面的数据,也就是可以使用组件里面的方法。
所以我们就可以根据这个调用,可以在方法里面使用axios来请求别的资源.在这之前需要下载包 npm install --save axios vue-axios。然后在main.js里面引用
import axios from ‘axios’
import VueAxios from ‘vue-axios’
Vue.use(VueAxios, axios);

代码(Profile.vue)

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

</template>

<script>
  export default {
    props: ['id'],
    name: "Profile",
    beforeRouteEnter(to,from,next){
        console.log("进入之前");
        next(vm=>{
          vm.getData()
        })
    },
    methos:{
         getData:function () {
             this.axios({
               method:'get',
               url:"http://localhost:8080/static/mock/data.json"
             }).then(function (response){
               console.log(response)
             })
         }
    }
  }
</script>

<style scoped>

</style>

代码(main.js)

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import VueAxios from 'vue-axios'



Vue.config.productionTip = false;
Vue.use(VueAxios, axios);
Vue.use(router)
Vue.use(ElementUI)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  //用于绑定App.vue
  render: h => h(App)
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值