美文网首页
vue使用路由Vue Router

vue使用路由Vue Router

作者: 空气KQ | 来源:发表于2019-08-26 15:38 被阅读0次

路由渲染位置

<router-view></router-view>

路由链接导航使用

<router-link to="/foo">Go to Foo</router-link>

当 <router-link> 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active

例子

image.png
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<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>
    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
</div>
<script>
    // 1. 定义 (路由) 组件。
    // 可以从其他文件 import 进来
    const Foo = {template: '<div>foo</div>'}
    const Bar = {template: '<div>bar</div>'}
    // 2. 定义路由
    // 每个路由应该映射一个组件。 其中"component" 可以是
    // 通过 Vue.extend() 创建的组件构造器,
    // 或者,只是一个组件配置对象。
    // 我们晚点再讨论嵌套路由。
    const routes = [
        {path: '/foo', component: Foo},//对应组件
        {path: '/bar', component: Bar}
    ]

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

</script>
</body>
</html>

[vm.$mount( [elementOrSelector] )]

如果 Vue 实例在实例化时没有收到 el 选项,则它处于“未挂载”状态,没有关联的 DOM 元素。可以使用 vm.$mount() 手动地挂载一个未挂载的实例。

组建内访问路由

this.$router 访问路由
this.$route 访问当前路由:

路由参数匹配

一个“路径参数”使用冒号 :标记。当匹配到一个路由时,参数值会被设置到this.$route.params,可以在每个组件内使用

const Foo = {template: '<div>foo id={{ $route.params.id }}</div>'}
const Bar = {template: '<div>bar</div>'}
const routes = [
        {path: '/foo/:id', component: Foo},//对应组件
        {path: '/bar', component: Bar}
    ]

<router-link to="/foo/50">Go to Foo id=50</router-link>
<router-link to="/foo/51">Go to Fooid=51</router-link>

url有搜索参数,可以使用$route.query

 <router-link to="/foo/50?name=22">Go to Foo id=50</router-link>
  const Foo = {template: '<div>foo id={{ $route.params.id }},name={{ $route.query.name }}</div>'}

url路径中有hash锚点

  <router-link to="/foo/51#name=nihaofsdfjdslsjlf">Go to Fooid=51</router-link>

  const Foo = {template: '<div>foo id={{ $route.params.id }},name={{ $route.query.name }},hash_name={{ $route.hash}}</div>'}

响应路由参数的变化

例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用

解决办法: watch (监测变化) ,使用 2.2 中引入的 beforeRouteUpdate 导航守卫


const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // 对路由变化作出响应...
    }
  }
}

路由规则

{
  // 会匹配所有路径
  path: '*'
}
{
  // 会匹配以 `/user-` 开头的任意路径
  path: '/user-*'
}

取得匹配路径

{{ this.$route.params.pathMatch }}

匹配优先级: 谁在前面,谁的优先级最高

嵌套路由

路由里面模板,再次嵌套<router-view></router-view>,定义子组件
children

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
    <h1>Hello App!</h1>

    <dl>
        <dt>
            <router-link to="/user/1">个人中心</router-link>
        </dt>
        <dd>
            <router-link to="/user/1/profile">个人文件</router-link>
        </dd>
        <dd>
            <router-link to="/user/1/posts">个人文章</router-link>
        </dd>
    </dl>


    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
</div>
<script>
    // 1. 定义 (路由) 组件。
    // 可以从其他文件 import 进来
    const User = {
        template: `
            <div class="user">
              <h2>User {{ $route.params.id }}</h2>
              <router-view></router-view>
            </div>
          `
    }
    const UserProfile = {template: '<div>个人文件</div>'}
    const UserPosts = {template: '<div>个人文章</div>'}
    const UserHome={
        template:'我是个人中心'
    }
    // 2. 定义路由
    // 每个路由应该映射一个组件。 其中"component" 可以是
    // 通过 Vue.extend() 创建的组件构造器,
    // 或者,只是一个组件配置对象。
    // 我们晚点再讨论嵌套路由。
    const routes=[

        { path: '/user/:id', component: User,

            children: [
                {
                    // 当 /user/:id/profile 匹配成功,
                    // UserProfile 会被渲染在 User 的 <router-view> 中
                    path: 'profile',
                    component: UserProfile
                },
                {
                    // 当 /user/:id/posts 匹配成功
                    // UserPosts 会被渲染在 User 的 <router-view> 中
                    path: 'posts',
                    component: UserPosts
                },
                { path: '', component: UserHome }
                ]
        }
        ]

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

</script>
</body>
</html>

image.png

编程式的导航

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

router.push(location, onComplete?, onAbort?)
当你点击 <router-link> 时,这个方法会在内部调用,所以说,点击 <router-link :to="..."> 等同于调用 router.push(...)
// 字符串
router.push('home')

// 对象
router.push({ path: 'home' })

// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})

// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

如果目的地和当前路由相同,只有参数发生了改变 (比如从一个用户资料到另一个 /users/1 -> /users/2),你需要使用 beforeRouteUpdate 来响应这个变化 (比如抓取用户信息)

router.replace 替换当前的URL历史记录

router.go(n) 历史url记录前进和后退

router.go(1)

// 后退一步记录,等同于 history.back()
router.go(-1)

// 前进 3 步记录
router.go(3)

// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
  const UserHome={

        created(){
            //跳转到个人文章
            let id=this.$route.params.id;
            router.push({ path: `/user/${id}/posts` }) // -> /user/123/posts
        }
    }

命名路由

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

const router = new VueRouter({
  routes: [
    {
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]
})

路由页面布局

有 sidebar (侧导航) 和 main (主内容) 两个视图,如果 router-view 没有设置名字,那么默认为 default

<div class="container" id="app">

    <router-view class="left one" name="left"></router-view>


    <router-view class="right" name="right"></router-view>

</div>
<script>
    const Left={
        template:'<ul><li>首页</li><li>你好</li></ul>'
    }
    const Right={
        template:'<div>中间内容</div>'
    }
    const router = new VueRouter({
        routes: [
            {
                path: '/',
                components: {
                    left: Left,
                    right: Right,

                }
            }
        ]
    })
    const app = new Vue({
        router
    }).$mount('#app');//手动挂载
</script>

重定向和别名

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 重定向的 字符串路径/路径对象
    }}
  ]
})
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
    <router-link to="/">a</router-link>
    <router-link to="/about">b</router-link>
    <router-link to="/tel">c</router-link>
    <router-view class="view one"></router-view>
</div>
<script>
    const Index={
        template:"<div>我是首页</div>"
    }
    const Tel={
        template:"<div>Tel</div>"
    }
    const About={
        template:"<h1>我是关于我们</h1>"
    }
    const router = new VueRouter({

        routes: [
            {
                path: '',
                redirect: { name: 'tel' }
            },
            {
                path: '/about',
                component:About
            },
            {
                path: '/tel',
                component:Tel,
                name:'tel'
            }
        ]
    })
    new Vue({
        router,
        el: '#app'
    })
</script>
</body>
</html>

点击a时跳转到c

别名

alias: '/b' 
image.png

组建传值

$route.params

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User }
  ]
})

通过 props 解耦
如果 props 被设置为 true,route.params 将会被设置为组件属性。
如果 props 是一个对象,它会被按原样设置为组件属性。当 props 是静态的时候有用。

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

    // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})

导航守卫

全局前置守卫

router.beforeEach((to, from, next) => {
  // ...
})
*   **`to: Route`**: 即将要进入的目标 [路由对象](https://router.vuejs.org/zh/api/#%E8%B7%AF%E7%94%B1%E5%AF%B9%E8%B1%A1)

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

*   **`next: Function`**: 一定要调用该方法来 **resolve** 这个钩子。执行效果依赖 `next` 方法的调用参数。

    *   **`next()`**: 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 **confirmed** (确认的)。

    *   **`next(false)`**: 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 `from` 路由对应的地址。

    *   **`next('/')` 或者 `next({ path: '/' })`**: 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 `next` 传递任意位置对象,且允许设置诸如 `replace: true`、`name: 'home'` 之类的选项以及任何用在 [`router-link` 的 `to` prop](https://router.vuejs.org/zh/api/#to) 或 [`router.push`](https://router.vuejs.org/zh/api/#router-push) 中的选项。

    *   **`next(error)`**: (2.4.0+) 如果传入 `next` 的参数是一个 `Error` 实例,则导航会被终止且该错误会被传递给 [`router.onError()`](https://router.vuejs.org/zh/api/#router-onerror) 注册过的回调。

全局后置钩子

你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:

router.afterEach((to, from) => {
  // ...
})

路由独享的守卫,组件独立的守卫

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

组件内的守卫

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}

beforeRouteEnter 守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。
不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数

beforeRouteEnter (to, from, next) {
  next(vm => {
    // 通过 `vm` 访问组件实例
  })
}

相关文章

网友评论

      本文标题:vue使用路由Vue Router

      本文链接:https://www.haomeiwen.com/subject/dvmrectx.html