zoukankan      html  css  js  c++  java
  • 路由vue-router

    一,安装

    1)npm install vue-router

    2)如果在一个模块化工程中使用它,必须要通过 Vue.use() 明确地安装路由功能:

    import Vue from 'vue'

    import VueRouter from 'vue-router'

    Vue.use(VueRouter)

    如果使用全局的 script 标签,则无须如此(手动安装)。

    二,使用

    // 0. 如果使用模块化机制编程,導入Vue和VueRouter,要调用 Vue.use(VueRouter)
    
    // 1. 定义(路由)组件。
    // 可以从其他文件 import 进来
    const Foo = { template: '<div>foo</div>' }
    const Bar = { template: '<div>bar</div>' }
    
    // 2. 定义路由
    // 每个路由应该映射一个组件。
    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')
    <!--这里的 <router-view> 是最顶层的出口,渲染最高级路由匹配到的组件。同样地,一个被渲染组件同样可以包含自己的嵌套 <router-view>-->
    <div id="app">
      <router-view></router-view>
    </div>
    //要在嵌套的出口中渲染组件,需要在 VueRouter 的参数中使用 children 配置
    const router = new VueRouter({
        routes: [
            {
                path: '/',
                redirect: '/main'//重定向
    },
            {
                path: '/main',
                component: MainView,
                children: [
                    {
                        path: '/main/visaindex',
                        component: visaIndex
                    },
                     {
                        path: '/main/personal',
                        component: Personal
                    }
                ]
            }
         ]
    });

    除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

    1)router.push(location)

    这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

    当你点击 <router-link> 时,这个方法会在内部调用,所以说,点击 <router-link :to="..."> 等同于调用router.push(...)。

    2)router.replace(location)

    跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。

    点击<router-link :to="..." replace>等同于调用router.replace(...)。

    3)router.go(n)

    这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步。

    4)『导航』表示路由正在发生改变。vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消。

    //使用 router.beforeEach 注册一个全局的 before 钩子

    router.beforeEach(function(to, from, next) {

    next();//确保要调用 next 方法,否则钩子就不会被 resolved

    })

    当一个导航触发时,全局的 before 钩子按照创建顺序调用。每个钩子方法接收三个参数:

    1to: Route: 即将要进入的目标 路由对象

    2from: Route: 当前导航正要离开的路由

    3next: Function: 一定要调用该方法来resolve这个钩子

     //注册一个全局的 after 钩子

    router.afterEach(function(route) {

    //...

    })

  • 相关阅读:
    php代码中注释的含义
    MySql-count(*)与count(id)与count(字段)之间的执行结果和性能分析
    mysql通配符进行模糊查询
    我的娃,我的宝贝
    Yii 2.0 query模式语法
    Yii 2.0版本调试输出SQL语句
    mysql高效率随机获取n条数据写法
    mysql语句中判断是否包含某字符串的方法
    应该让老婆多休息
    win10常用快捷键总结
  • 原文地址:https://www.cnblogs.com/colorful-coco/p/6366159.html
Copyright © 2011-2022 走看看