search
HomeWeb Front-endJS TutorialDetailed introduction to Vue Router, the routing manager in Vue.js (with code)

This article brings you a detailed introduction to the routing manager Vue Router in Vue.js (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Preparation

HTML

<script></script>
<script></script>

<div>
  <h1 id="Hello-App">Hello App!</h1>
  <p>
    <!-- 使用 router-link 组件来导航. -->
    <!-- 通过传入 `to` 属性指定链接. -->
    <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
    <router-link>Go to Foo</router-link>
    <router-link>Go to Bar</router-link>
  </p>
  <!-- 路由出口 -->
  <!-- 路由匹配到的组件将渲染在这里 n内置组件-->
  <router-view></router-view>
</div>

JavaScript

// 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)

// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Foo = { template: '<p>foo</p>' }
const Bar = { template: '<p>bar</p>' }

// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
  router
}).$mount('#app')

// 现在,应用已经启动了!

By injecting the router , we can access the router through this.$router in any component, or access the current route through this.$route:

export default {
  computed: {
    username () {
      // 我们很快就会看到 `params` 是什么
      return this.$route.params.username
    }
  },
  methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
}

routes options (Array)

redirect

//此时访问/a会跳转到/b
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})
//重定向的目标也可以是一个命名的路由:
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: { name: 'foo' }}
  ]
})
//甚至是一个方法,动态返回重定向目标:
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: to => {
      // 方法接收 目标路由 作为参数
      // return 重定向的 字符串路径/路径对象
    }}
  ]
})

Named route

export default [
    {
        path:'/',
        redirect:'/app' //默认跳转路由
    },
    {
        path: '/app',
        //路由命名,可用于跳转
        name: 'app',
    }
]

//可用于跳转
<router-link>app</router-link>

Route meta information

You can configure the meta field when defining a route:

export default [
    {
        path:'/',
        redirect:'/app' //默认跳转路由
    },
    {
        path: '/app',
        //**相当于HTML的meta标签**
        meta: {
            title: 'this is app',
            description: 'asdasd'
        },
    }
]

Nested routing

export default [
    {
        path:'/',
        redirect:'/app' //默认跳转路由
    },
    {
        path: '/app',
        //子路由 匹配 /app/test
         children: [
           {
             path: 'test',
             component: Login
           }
         ]
    }
]

Routing component parameter passing

export default [
    {
        path:'/',
        redirect:'/app' //默认跳转路由
    },
    {
        path: '/app/:id', // /app/xxx ,组件内部可以通过$route.params.id拿到这个值
        // 会把:后面的参数通过props传递给组件Todozhong 中
        //布尔模式
        props: true,
        //对象模式
        props:{id:456}
        //函数模式
        props: (route) => ({ id: route.query.b }),
        component: Todo,

    }
]

mode option (string)

vue-router default hash mode - uses the hash of the URL to simulate a complete URL, so when the URL changes , the page will not reload.

If we don’t want an ugly hash, we can use the routing history mode, which makes full use of the history.pushState API to complete URL jumps without reloading the page.

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

To play this mode well, you also need background configuration support.

base(string)

The base path of the application. For example, if the entire single-page application is served under /app/, then base should be set to "/app/"

return new Router({
    routes,
    mode: 'history',//默认使用hash#
    base: '/base/', //在path前面都会加上/base/,基路径
  })

linkActiveClass(string)

Default value: "router-link-active"

The default "activation class class name" of global configuration .

return new Router({
    routes,
    mode: 'history',//默认使用hash#
    base: '/base/', //在path前面都会加上/base/,基路径
    // 点击calss名字
    linkActiveClass: 'active-link', //匹配到其中一个子集
    linkExactActiveClass: 'exact-active-link',//完全匹配
  })

linkExactActiveClass(string)

Default value: "router-link-exact-active"

Global configuration< ;router-link> Exactly activate the default class.

scrollBehavior(Function)

Whether to scroll after routing jump

export default () => {
  return new Router({
    routes,
    mode: 'history',//默认使用hash#
    base: '/base/', //在path前面都会加上/base/,基路径
    //页面跳转是否需要滚动
    /*
        to:去向路由,完整路由对象
        from:来源路由
        savedPosition:保存的滚动位置
    */
    scrollBehavior (to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition
      } else {
        return { x: 0, y: 0 }
      }
    },
  })
}

parseQuery / stringifyQuery (Function)

/每次import都会创建一个router,避免每次都是同一个router
export default () => {
  return new Router({
    routes,
    mode: 'history',//默认使用hash#
    base: '/base/', //在path前面都会加上/base/,基路径
    // 路由后面的参数?a=2&b=3,string->object
     parseQuery (query) {

     },
      //object->string
    stringifyQuery (obj) {

     }
  })
}

fallback(boolean)

When the browser does not support history.pushState, control whether routing should Fall back to hash mode. The default value is true.
If set to false, the page will be refreshed after the jump, which is equivalent to a multi-page application

Transition animation

is a basic dynamic component, so we can use the component to add some transition effects to it:

<transition>
  <router-view></router-view>
</transition>

Advanced usage

Named view

<router-view></router-view>
<router-view></router-view>
<router-view></router-view>

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
      //默认组件
        default: Foo,
        //命名组件
        a: Bar,
        b: Baz
      }
    }
  ]
})

Navigation guard

Global guard

import Vue from 'vue'
import VueRouter from 'vue-router'

import App from './app.vue'

import './assets/styles/global.styl'
// const root = document.createElement('p')
// document.body.appendChild(root)
import createRouter from './config/router'
Vue.use(VueRouter)

const router = createRouter()

// 全局导航守卫(钩子)

// 验证一些用户是否登录
router.beforeEach((to, from, next) => {
    console.log('before each invoked')
    next()
//   if (to.fullPath === '/app') {
//     next({ path: '/login' })
//     console.log('to.fullPath :'+to.fullPath )

//   } else {
//     next()
//   }
})

router.beforeResolve((to, from, next) => {
    console.log('before resolve invoked')
    next()
})

// 每次跳转后触发
router.afterEach((to, from) => {
    console.log('after each invoked')
})

new Vue({
    router,
    render: (h) => h(App)
}).$mount("#root")

Exclusive to routing Guard

You can define beforeEnter directly in the routing configuration. Guard:

export default [
    {
        path:'/',
        redirect:'/app' //默认跳转路由
    },
    {
  
        path: '/app',
        // 路由独享的守卫钩子
        beforeEnter(to, from, next) {
            console.log('app route before enter')
            next()
        }
        component: Todo,
    }
]

Guard within the component

export default {
  //进来之前
  beforeRouteEnter(to, from, next) {
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
    console.log("todo before enter", this); //todo before enter undefined
    //可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
    next(vm => {
        // 通过 `vm` 访问组件实例
      console.log("after enter vm.id is ", vm.id);
    });
  },
  //更新的时候
  beforeRouteUpdate(to, from, next) {
    console.log("todo update enter");
    next();
  },
  // 路由离开
  beforeRouteLeave(to, from, next) {
    console.log("todo leave enter");
    const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
      if (answer) {
        next()
      } else {
        //以通过 next(false) 来取消。
        next(false)
      }
  },
  props:['id'],
  components: {
    Item,
    Tabs
  },
  mounted() {
    console.log(this.id)
  },
};

Related recommendations:

Response in Vue A brief introduction to formula data (pictures and text)

A brief introduction to global registration and local registration in vue.js components and example analysis

The above is the detailed content of Detailed introduction to Vue Router, the routing manager in Vue.js (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
总结分享几个 VueUse 最佳组合,快来收藏使用吧!总结分享几个 VueUse 最佳组合,快来收藏使用吧!Jul 20, 2022 pm 08:40 PM

VueUse 是 Anthony Fu 的一个开源项目,它为 Vue 开发人员提供了大量适用于 Vue 2 和 Vue 3 的基本 Composition API 实用程序函数。本篇文章就来给大家分享几个我常用的几个 VueUse 最佳组合,希望对大家有所帮助!

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

聊聊Vue3+qrcodejs如何生成二维码并添加文字描述聊聊Vue3+qrcodejs如何生成二维码并添加文字描述Aug 02, 2022 pm 09:19 PM

Vue3如何更好地使用qrcodejs生成二维码并添加文字描述?下面本篇文章给大家介绍一下Vue3+qrcodejs生成二维码并添加文字描述,希望对大家有所帮助。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

Github 上 8 个不可错过的 Vue 项目,快来收藏!!Github 上 8 个不可错过的 Vue 项目,快来收藏!!Jun 17, 2022 am 10:37 AM

本篇文章给大家整理分享8个GitHub上很棒的的 Vue 项目,都是非常棒的项目,希望当中有您想要收藏的那一个。

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何使用VueRouter4.x?快速上手指南如何使用VueRouter4.x?快速上手指南Jul 13, 2022 pm 08:11 PM

如何使用VueRouter4.x?下面本篇文章就来给大家分享快速上手教程,介绍一下10分钟快速上手VueRouter4.x的方法,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!