Home  >  Article  >  Web Front-end  >  Detailed introduction to Vue Router, the routing manager in Vue.js (with code)

Detailed introduction to Vue Router, the routing manager in Vue.js (with code)

不言
不言Original
2018-08-14 17:03:081709browse

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 src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- 使用 router-link 组件来导航. -->
    <!-- 通过传入 `to` 属性指定链接. -->
    <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">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 :to="{name:&#39;app&#39;}">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 class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></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