vue-router基本使用

269 阅读1分钟

1、vue-router基本使用步骤:

①、创建路由组件

②、创建路由器并把路由组件映射成路由

③、注册路由器

④、使用路由标签操作或显示路由组件内容

:用来生成路由链接 

:用来显示当前路由组件界面

2、代码案例

2.1、路由组件

src/views/About.vue

<template>  
   <div>About</div>
</template>
<script>
   export default {}
</script>
<style>
   
</style>

src/views/Home.vue

<template>  
   <div>Home</div>
</template>
<script>
   export default {}
</script>
<style>
   
</style>

2.2、主vue组件

src/App.vue

<template>  <div>        <div class="row">              <div class="col-xs-offset-2 col-xs-8">                    <div class="page-header">                <h2>Router Basic - 01</h2>            </div>              </div>        </div>        <div class="row">              <div class="col-xs-2 col-xs-offset-2">                      <div class="list-group">                              <!-- 这里的路径要和路由器里的配置路径一致 -->                              <router-link to="/about" class="list-group-item">                    About                </router-link>                              <router-link to="/home" class="list-group-item">                    Home                </router-link>                      </div>              </div>              <!-- 显示路由组件 -->              <div class="col-xs-6">                    <div class="panel">                          <div class="panel-body">                              <router-view>                </router-view>                          </div>                    </div>              </div>        </div>  </div></template><script>    export default {}</script><style></style>

2.3、路由器

src/router/index.js

/* 路由器 */import VueRouter from "vue-router";import Vue from "vue";import About from "../views/About.vue";import Home from "../views/Home.vue";Vue.use(VueRouter);/* 向外暴露一个路由器,在构造器内配置路由 */export default new VueRouter({      /* 配置n个路由 把路由组件映射成路由 */      routers: [{        path: '/about',        component: About    },    {        path: '/home',        component: Home    },    {        path: '/',        redirect: '/about'    }]});

2.4、主程序的

src/main.js

import Vue from 'vue'import App from './App.vue'import router from './router'new Vue({     /* 配置对象的属性名都是一些固定的,不能修改 */      el: '#app',      components: { App },      template: '<App/>',      router      /* 注册路由器 */})

2.5、主页面

index.html

<!DOCTYPE html><html>  <head>        <meta charset="utf-8">        <meta name="viewport" content="width=device-width,initial-scale=1.0">    <link rel="stylesheet" href="./static/css/bootstrap.css">        <title>vue_router_demo</title>        <style>              .router-link-active{                    color: red !important;              }        </style>  </head>  <body>        <div id="app"></div>        <!-- built files will be auto injected -->  </body></html>

3、工程样例图片