vue-router 路由进阶学习

版权声明:前端菜鸟--人间草木所有 https://blog.csdn.net/qq_43258252/article/details/87294278

一、vue-router 路由跳转

1、router-link标签跳转

在html标签内使用router-link跳转,相应于超链接a标签,使用方式如下:

<router-link to="/">[显示字段]</router-link>

to:导航路径

使用示例如下:

<p>导航 :
   <router-link to="/">首页</router-link>
   <router-link to="/hello">hello</router-link>
</p>

2、编程式导航-JS代码内部跳转

实际项目中,很多时候都是通过在JS代码内部进行导航的跳转,使用方式如下:

this.$router.push('/xxx')

具体的简单用法:

(1)先编写一个按钮,在按钮上绑定goHome( )方法。

<button @click="goHome">回到首页</button>

(2)在<script>模块里加入goHome方法,并用this.$router.push(‘/’)导航到首页

export default {
    name: 'app',
    methods: {
        goHome(){
            this.$router.push('/home');
        }
    }
}

3、其他常用方法

//  后退一步记录,等同于 history.back()
this.$router.go(-1)
this.$router.back(-1)
// 在浏览器记录中前进一步,等同于 history.forward()
this.$router.go(1)

二、vue-router 的重定向-redirect

三、Vue 去除hash路由默认的#

 

四、Vue 路由懒加载

五、Vue router 全局路由守卫

// 全局路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === `${base}login`) {
    return next()
  }

  // token验证,如果存储在sessionStorage里的auth的值丢失,就回到登陆页面,(开发时可以注释掉)
  // if (!sessionStorage.getItem('auth')) {
  //   return next(`${base}login`)
  // }

  // 如果页面在 /  默认页面,跳转到登陆页面(和vue路由重定向功能类似)
  if (to.path === `${base}`) {
    return next(`${base}login`)
  }
  next()
})

六、Vue router 404页面设置

如果访问的路由不存在,或者用户输入错误时,会有一个404友好的提示页面,配置如下:

1.在src/components/error404.vue中编写如下代码:

<template>
  <div class="error404">
    <h1>404 not found</h1>
    <h1>您访问的网页不存在</h1>
  </div>
</template>
<script>
export default {
  name: 'error404',
  data () {
    return {

    }
  }
}
</script>

<style scoped lang="less">
</style>

2.在/src/router/index.js中加入如下代码:

  {
    // 404页面配置  如果访问的路由不存在,或者用户输入错误时,会有一个404友好的提示页面
    path: `*`,
    component: () => import('../components/error404.vue')
  }

猜你喜欢

转载自blog.csdn.net/qq_43258252/article/details/87294278