Vue Router 使用实例

2019-01-03  本文已影响0人  UULU

在对Vue Router不熟练的情况下,很容易走弯路,过后才会发现原来还有捷径。我的原则是一个变量能解决的问题绝对不会用两个,如果不用自己定义变量是最好的。

下面是核心用法的总结,这个实例包含了以下这些知识点 (非完整实例,未给出无关的代码)

src/router.js

项目中直接使用了path跳转,所有未指定name属性

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 实现“懒加载组件”的通用函数
function component(comp) {
  return () =>
    import(/* webpackChunkName: "comp-[request]" */ `@/components/${comp}`)
}

function view(comp) {
  return () =>
    import(/* webpackChunkName: "view-[request]" */ `@/view/${comp}`)
}

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      component: loadComponent('Login')
    },
    {
      // '/home' 重定向到 `/`
      path: '/home',
      redirect: '/'
    },
    {
      path: '/',
      component: view('Home'),
      children: [
        {
          // 关联 `/` 根路径的组件
          path: '/',
          component: component('Main')
        },
        {
          // 关联 `/profile` 路径的子组件
          path: '/profile',
          component: component('home/Profile')
        },
        {
          // 关联 `/hero/{英雄ID}` 带params路径的组件
          path: '/hero/:heroId',
          component: component('Hero')
        }
      ]
    },
    {
      path: '/about',
      component: view('About')
    },
    {
      // 自定义 404 页面,否则会打开默认界面
      path: '*',
      component: view('NotFound')
    }
  ]
})

src/App.vue

<template>
  <div id="app"><router-view /></div>
</template>

src/components/Home.vue

组件的key属性可以唯一标记组件,如果不指定 ,不同的path指向同一个component,vue 会直接重用这个组件,而不会重新触发created()

<template>
  <div class="home">
    <div class="header">
      <ul>
        <!-- 遍历数组初始化菜单 -->
        <!-- 匹配当前path的菜单项,样式修改为 'menu-active' -->
        <li
          v-for="(item, index) in menus"
          :key="index"
          :class="item.path == $route.path? 'menu-active': 'menu'"
          @click="onClick(item)"
        >
          {{ item.title }}
        </li>
      </ul>
    </div>
    <div class="main">
      <!-- 用path绑定组件的Key,解决带params路径跳转,页面不刷新的问题 -->
      <router-view :key="$route.path"></router-view>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        menus: [
          {
            title: '首页',
            path: '/'
          },
          {
            title: '关于',
            path: '/about'
          }
        ]
      }
    },
    methods: {
      onClick(item) {
        this.$router.push(item.path)
      }
    }
  }
</script>
上一篇 下一篇

猜你喜欢

热点阅读