Vue:404 路由钩子(狂神)

(1)显示登录的姓名 

 创建组件:

Profile.vue

<template>
  <div>
    <h1>个人信息</h1>
    <!--{{$route.params.id}}-->
    {{id}}
  </div>

</template>

<script>
    export default {
        props:['id'],
        name: "Profile"
    }
</script>

<style scoped>

</style>

List.vue:

<template>
    <h1>用户列表</h1>
</template>

<script>
    export default {
        name: "List"
    }
</script>

<style scoped>

</style>

Login.vue:

设置:

this.$router.push("/main/"+this.form.username);

<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">欢迎 登录</h3>
      <el-form-item label=" 账号" prop="username">
        <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
      </el-form-item>
      <el-form-item label=" 密码" prop="password">
        <el-input type="password" placeholder=" 请输入密码" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onSubmit( 'loginForm' )">登录</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="温馨提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handLeClose">
      <span>请输入账号和密码</span>
      <span slot="footer" class="dialog- footer">
        <el-button type="primary" @click="dialogVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      return {
        form: {
          username: '',
          password: ''
        },
        //表单验证,需要在el-form-item 元素中增加prop 属性
        rules: {
          username: [
            {required: true, message: " 账号不可为空", trigger: 'blur'}
          ],
          password: [
            {required: true, message: " 密码不可为空 ", trigger: 'blur'}
          ]
        },
       //对话框显示和隐藏
        dialogVisible: false
      }
    },
    methods: {
      onSubmit(formName) {
    //为表单绑定验证功能
        this.$refs[formName].validate((valid) => {
          if (valid) {//只要不为空就通过
        //使用vue-router路由到指定页面,该方式称之为编程式导航
            this.$router.push("/main/"+this.form.username);
          } else {
            this.dialogVisible = true;
            return false;
          }
        });
      }
    }
  }
</script>


<style lang="scss" scoped>
.login-box {
  border: 1px solid #DCDFE6;
  width: 350px;
  margin: 180px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 25px #909399;
}

.login-title {
  text-align: center;
  margin: 0 auto 40px auto;
  color: #303133;
}
</style>

Main.vue:接收name

<span>{{name}}</span>

<template>
  <div>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1']">

          <el-submenu index="1">
            <template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
            <el-menu-item-group>
              <el-menu-item index="1-1">
                <!--插入的地方-->
                <!--name:传组件名 params:传递参数-->
                <router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>
              </el-menu-item>
              <el-menu-item index="1-2">
                <!--插入的地方-->
                <router-link to="/user/list">用户列表</router-link>
              </el-menu-item>

              <el-menu-item index="1-3">
                <!--插入的地方-->
                <router-link to="/goHome">回到首页</router-link>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>

          <el-submenu index="2">
            <template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
            <el-menu-item-group>
              <el-menu-item index="2-1">分类管理</el-menu-item>
              <el-menu-item index="2-2">内容列表</el-menu-item>
            </el-menu-item-group>
          </el-submenu>

        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <el-dropdown>
            <i class="el-icon-setting" style="margin-right: 15px"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>个人信息</el-dropdown-item>
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span>{{name}}</span>
        </el-header>

        <el-main>
          <!--在这里展示视图-->
          <router-view />
        </el-main>

      </el-container>
    </el-container>
  </div>
</template>
<script>
  export default {
    props:['name'],
    name: "Main"
  }
</script>
<style scoped lang="scss">
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }
  .el-aside {
    color: #333;
  }
</style>

设置路由:

index.js:接收name,利用props设置为true

import Vue from 'vue'
import Router from 'vue-router'

//导入组件
import Main from '../view/Main'
import Login from '../view/Login'

import UserList from '../view/user/List'
import UserProfile from '../view/user/Profile'


Vue.use(Router);

export default new Router({
  routes:[
    {
      path:'/main/:name',//接收name
      component:Main, //嵌套路由
      props:true, //使用pros取
      children:[
        //:id
        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile,props:true},
        {path:'/user/list',component:UserList}
      ]
    },
    {
      path:'/login',
      component:Login
    },
    {// 重定向
      path:'/goHome',
      redirect:'/main'
    }
  ]
});

在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'

//安转路由
Vue.use(router)
Vue.use(ElementUI)

new Vue({
  el: '#app',
  router,
  render: h => h(App) //ElementUI
})

App.vue:

<template>
  <div id="app">
    <router-link to="/login">login</router-link>
    <router-view></router-view>
  </div>
</template>

<script>


export default {
  name: 'App',

}
</script>


index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>hello-vue</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

 

 

路由模式修改: index.js添加:

mode:'history'
import Vue from 'vue'
import Router from 'vue-router'

//导入组件
import Main from '../view/Main'
import Login from '../view/Login'

import UserList from '../view/user/List'
import UserProfile from '../view/user/Profile'
import NotFound from '../view/NotFound'


Vue.use(Router);

export default new Router({
  mode:'history',//设置路径不带#号
  routes:[
    {
      path:'/main/:name',//接收name
      component:Main, //嵌套路由
      props:true, //使用pros取
      children:[
        //:id
        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile,props:true},
        {path:'/user/list',component:UserList}
      ]
    },
    {
      path:'/login',
      component:Login
    },
    {// 重定向
      path:'/goHome',
      redirect:'/main'
    },
    {
      path:"*",
      component:NotFound
    }
  ]
});

 地址栏就不带#了

404页面

创建NotFound.vue

<template>
    <div><H1>404,没有页面</H1></div>
</template>

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

<style scoped>

</style>

添加路由:导入组件,设置路由路径

index.js

import Vue from 'vue'
import Router from 'vue-router'

//导入组件
import Main from '../view/Main'
import Login from '../view/Login'

import UserList from '../view/user/List'
import UserProfile from '../view/user/Profile'
import NotFound from '../view/NotFound'


Vue.use(Router);

export default new Router({
  mode:'history',//设置路径不带#号
  routes:[
    {
      path:'/main/:name',//接收name
      component:Main, //嵌套路由
      props:true, //使用pros取
      children:[
        //:id
        {path:'/user/profile/:id',name:'UserProfile',component:UserProfile,props:true},
        {path:'/user/list',component:UserList}
      ]
    },
    {
      path:'/login',
      component:Login
    },
    {// 重定向
      path:'/goHome',
      redirect:'/main'
    },
    {
      path:"*",
      component:NotFound
    }
  ]
});

当输入地址错误时,都跳转到这个页面 

 

除了之前的钩子函数还存在两个钩子函数

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

Profile.vue:

<template>
  <div>
    <h1>个人信息</h1>
    <!--{{$route.params.id}}-->
    {{id}}
  </div>

</template>

<script>
    export default {
        props:['id'],
        name: "Profile",
        beforeRouteEnter:(to,from,next)=>{
          console.log("进入路由之前");
          next(vm=>{
            vm.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>

 

 

 

参数说明:

to:路由将要跳转的路径信息

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

  • 安装Axios   cnpm install  --save axios vue-axios
  • main.js引用 Axios

在main.js中添加

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

data.json

{
  "name": "cv战士",
  "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "含光门",
    "city": "陕西西安",
    "country": "中国"
  },
  "links": [
    {
      "name": "bilibili",
      "url": "https://bilibili.com"
    },
    {
      "name": "cv战士",
      "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343"
    },
    {
      "name": "百度",
      "url": "https://www.baidu.com/"
    }
  ]
}

 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下

在 beforeRouteEnter 中进行异步请求,上面Profile.vue已经写了

 请求到了json数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵俺第一专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值