0
点赞
收藏
分享

微信扫一扫

路由模式、处理404、路由钩子与异步请求 2022-3-19

伊人幽梦 2022-03-19 阅读 73
vue.js学习

一、当用户登录后主页显示用户的用户名

login.vue
在这里插入图片描述
index.js
在这里插入图片描述
main.vue
在这里插入图片描述

在这里插入图片描述
结果:
在这里插入图片描述

二、路由模式(mode:‘history’)

路由模式有两种:
hash(默认):路径代#符号,如http://localhost/#/login
history:路径不带#符号,如http://localhost/login

export default {
  //路由模式
  mode:‘’history’,
  name: "Login",
  data(){
    return{
      form: {
        username:'',
        password:''
      },

在这里插入图片描述

三、处理404

3.1新建一个vue

在这里插入图片描述
NotFound.vue

<template>
  <div>
    <h1>404,你的页面走丢了</h1>
  </div>
</template>

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

在这里插入图片描述

index.js

import NotFound from '../views/NotFound'

在这里插入图片描述

    {
      path: '*',
      component: NotFound
    }

在这里插入图片描述

四、路由钩子与异步请求

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

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

4.1、安装Axios

cnpm install axios -s
在这里插入图片描述

4.2、main.js 引用Axios

import axios from ‘axios’;
import VueAxios from ‘vue-axios’;

Vue.use(VueAxios,axios);
在这里插入图片描述

4.3引入axios,

在这里插入图片描述

data.json

{
  "name": "vue",
  "url": "https://www.bilibili.com/",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "xxx",
    "city": "北京",
    "country": "中国"
  },
  "links": [
    {
      "name": "bilbili",
      "url": "https://space.bilbili.com/95256449"
    },
    {
      "name": "狂胜说java",
      "url": "https://blog.kuangstudy.com"
    },
    {
      "name": "百度",
      "url": "https://www.baidu.com/"
    }
  ]
}

npm run dev
在这里插入图片描述

Profile.vue

<template>
<!--所有的元素,必须不能在根节点下-->
  <div>
    <h1>个人信息</h1>
    {{id}}
  </div>
</template>

<script>
export default {
  name: "UserProfile",
  props:['id'],
  beforeRouteEnter:(to,from,next)=>{
    console.log("进入路由之前");//加载数据
    next(vm =>{
      vm.getDate();//进入路由之前执行getDat方法
    });
  },
  beforeRouteLeave:(to,from,next)=>{
    console.log("进入路由之后");
    next();
  },
  methods:{
    getDate: function () {
      this.axios({
        method: 'get',
        url: 'http://localhost:8080/static/mock/data.json'
      }).then(function (response){
        console.log(response)
      })
    }
  }
}
</script>

<style scoped>

</style>
举报

相关推荐

0 条评论