vue-router学习

来源:互联网 发布:python subprocess pid 编辑:程序博客网 时间:2024/06/11 08:46

alias别名

在路由配置文件中:

export default new Router ({  routes : [      {      path: '/',      name: 'Hello',      component: Hello    },    {      path: '/params/:newId/:newTitle',      name : 'params',      component : Params    },     {      path : '/goHome',      redirect : '/'    },    {      path : '/goParams/:newId/:newTitle',      redirect: '/params/:newId/:newTitle'    },    {      path: '/first1',      component: First1,      alias : '/firstOne'    }  ]})

这样当url为http://localhost:8080/#/firstOnehttp://localhost:8080/#/first1则会进入同一个界面,这与之前redirect的差别就在这个url的内容是什么

这种情况起别名不生效:

  routes : [      {      path: '/',      name: 'Hello',      component: Hello,      alias: '/home'    }]

路由里的钩子函数

有一个进入路由之前配置(BeforeEnter),另一个就是离开路由之前

配置方法:

第一个就是在src/router/index.js

    {      path: '/params/:newId/:newTitle',      name : 'params',      component : Params,      beforeEnter:(to, from, next) => {        console.log(to);        console.log(from);        next();  /*相当于开关,可以跳转,看可以有参数,true为跳转,false为*/      }    }

另一种写在模板中的配置方法

    export default {        name : 'params',        data() {            return {                msg : 'params pages'            }        },        beforeRouteEnter: (to, from, next) => {            console.log("准备进入params路由模板");            next();        },        beforeRouteLeave: (to, from, next) => {            console.log("准备离开params路由模板");            next();        }    }

编程式导航

    <div>      <button @click="goback">后退</button>      <button @click="goNext">前进</button>    </div>
export default {  name: 'app',  methods : {    goback() {      this.$router.go(-1);    },    goNext() {      this.$router.go(1);    }  }}

使用this.$router.push('/***')跳转到任意一页

<button @click="goHome">返回首页</button>
goHome() {  this.$router.push('/');}

mode的作用

url从之前的http://localhost:8080/#/firstOne 到 http://localhost:8080/firstOne

之需要设置路由配置文件就可以,这样子

export default new Router ({  mode : 'history',  routes : [      {      path: '/',      name: 'Hello',      component: Hello,      alias: '/home'      }  ]})

当mode为hash时,就是这样http://localhost:8080/#/firstOne

404错误

Error.vue界面:

<template>    <div>        <h2>{{msg}}</h2>    </div></template><script type="text/javascript">    export default {        name : 'Error',        data () {            return {                msg : '404 error: 页面不存在'            }        }    }</script>

配置路由:

    {      path: '*',      component: Error    }