乐趣区

Vue-路由的配置

什么是路由

vue 路由是可以通过组件的形式把所有的组件组装成为一个应用程序,当我们需要的时候,将这个组件映射到路由,然后告诉 Vue 我们在哪里渲染它们。

路由是我们浏览器的一个地址。

vue 路由的优缺点

当我们加载一个程序时,由于它加载的内容特别多,所以会比较缓慢,但是我们加载完之后,我们到页面里进行切换,它的切换速度会变得特别快。原因是因为我们将所有的程序都放在一个页面里面了,我们将它加载时所有的功能所有的主键都加载到一个页面去了,所以它加载的速度特别慢,但是加载完之后我们再进行后续的操作时,它的切换速度和反应速度回特别快。

路由配置安装

路由最主要的配置是在于切换和跳转页面这两个方面。

  • 路由配置
  • 动态效果
  • 命名路由
  • 嵌套路由
<!DOCTYPE html>
<html>
  <meta charset="utf-8">
  <title>Vue 路由的配置 </title>
<head>
  <meta charset="utf-8">
  <title>Vue 内置指令 </title>
  <script src="Vue.min.js"></script>
  <script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router@3.1.2/dist/vue.js"></script>

  <style>
    * {
      padding: 0;
      margin: 0;
    }
    body {background: #F4F5F6;}
    a {
      text-decoration: none;
      color: #000;
    }
    #main {
      width:980px;
      margin: 0 auto;
      margin-top: 80px;
    }
    #main-left {
      width: 180px;
      float: left;
    }
    #main-left a {
      display: block;
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: center;
    }
    #main-right {
      width: 730px;
      float: right;
      background: #fff;
      padding: 20px;
    }
    .active {color: #007Aff !important;}

  </style>
</head>

<body>
  <div id="main">
    <!-- 导航栏 -->
    <div id="main-left">
      <router-link to="/home" @click.native="changeIndex(1);" :class="{active : index == 1}"> 网站首页 </router-link>
      <router-link to="/about" @click.native="changeIndex(2);" :class="{active : index == 2}"> 关于我们 </router-link>
    </div>
    <!-- 对应显示的内容 -->
    <div id="main-right">
      <router-view></router-view>
    </div>
  </div>

</body>

<script>
  // 定义组件模块
  const Home = {template: '<div><h1>Vue</h1><p>Vue 课程 </p></div>'};
  const About = {template: '<div><div><router-link to="/about/ha"> 关于内容 </router-link> | <router-link to="/home/hb"> 关于课程 </router-link></div>'};
  const Ha = {template: '<div><h1> 关于内容 </h1><p> 关于内容........</p></div>'};
  const Hb = {template: '<div><h1> 关于课程 </h1><p> 关于课程........</p></div>'};

  // 定义路由
  const router = new VueRouter({
    routes: [{ path: '/', redirect: '/home'},
      {path: '/home', component: Home},
      { 
        path: '/about',
        component: About,
        children: [
          {
            path: 'ha',
            component: Ha
          },
          {
            path: 'hb',
            component: Hb
          }
        ]
      },
    ]
  });

  // 创建 vue 实例并使用路由配置
  var vm = new Vue({
    router,
    data: {index: 1},
    methods: {changeIndex: function(index) {this.index = index;}
    }
  }).$mount('#main');
</script>
</html>

官方文档:http://router.vuejs.org/zh-cn…

下载地址:http://unpkg.com/vue-router/d…

退出移动版