Vue 路由模式和404

路由模式有两种

  • hash:路径带#符号,如:http://localhost/#/login
  • history:路径不带#符号,如:http://localhost/login

修改路由配置,如下:

/**
 * 配置路由
 */
import Vue from 'vue'
import Router from 'vue-router'
import Main from '../views/Main'
import Login from '../views/Login'
import UserList from '../views/user/List'
import UserProfile from '../views/user/Profile'
Vue.use(Router);
export default new Router({
  mode:'history',
  routes:[
    {
      path:'/login',
      component:Login
    },{
      path:'/main/:username',
      component:Main,
      props:true,
      children:[ //嵌套路由
        {
          path:'/user/profile/:id',
          name:'UserProfile',
          component:UserProfile,
          props:true
        },
        {path:'/user/list',component:UserList}
      ]
    },
    {
      path:'/goHome',
      redirect:'/main'
    }
  ]
});

路由钩子与异步请求

beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行
<template>
  <div>
    <h1>个人信息</h1>
    {{id}}
  </div>

</template>

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

    }
</script>

<style scoped>

</style>

参数说明

  • to:路由将要跳转的路径信息
  • from:路径跳转前的路径信息
  • next:路由的控制参数

    next() :跳转下一个页面

    next('/path'):改变路由的跳转方向,使其跳到另一个路由

    next(false):返回原来的页面

    next((vm)=>{}):仅在beforRouteEnter中可用,vm是组件实例

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

1.安装Axios
cnpm install axios -s
2.在main.js引用axios 和 vue-axios
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

 3.在static文件夹下创建测试数据文件夹 mock 并建立data.js文件

{
  "name": "创客未来",
  "url": "https://www.baidu.com",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "hanguangmen",
    "city": "shanxixian",
    "country": "zhongguo"
  },
  "links": [
    {
      "name": "bilibili",
      "url": "https://www.baidu.com"
    },
    {
      "name": "bilibili",
      "url": "https://www.baidu.com"
    }
  ]
}

4.测试正常访问json数据

 

 

 5.在个人信息组件Profile.vue中编写数据请求代码

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

</template>

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

<style scoped>

</style>
posted @ 2021-01-23 18:33  创客未来  阅读(240)  评论(0编辑  收藏  举报