vue part4 vue-router

文档 https://router.vuejs.org/zh-cn

npm  install vue-router --save

调用

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
View Code

流程

a. views目录内组件

b. router目录映射路由js   (路径与a中组件)

c. main.js 对象属性router

d. 标签router-link / router-view

1.基本路由

index.html

routeview 标签选中自带class .router-link-active  ,定义样式

<!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_demo</title>

    <style>
      .router-link-active {
        color: red !important;
      }
    </style>

  </head>

  <body>
    <div id="app">

    </div> <!--app -->
  </body>

</html>
View Code

views/About.vue

与路由相关组件放置与views目录下

<template>
<div>about</div>
</template>

<script>
export default {

}

</script>

<style>

</style>
View Code

views/Home.vue

<template>
<div>home</div>
</template>

<script>
export default {

}

</script>

<style>

</style>
View Code

router/index.js

绑定path与对应views下的组件

/**
 * Created by infaa on 2018/9/21.
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import About from '../views/About.vue'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

export default new VueRouter({
  routes: [
    {
      path: '/about',
      component: About
    },
    {
      path: '/home',
      component: Home
    },
    {
      path: '/',
      redirect: '/about'
    }
  ]

})
View Code

app.js

使用router 方法,利用router-link  to=''xxx“区分  ,router-view 自动匹配到views下的组件

<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>
View Code

main.js 需要注册router

/**
 * Created by infaa on 2018/9/19.
 */
import Vue from 'vue'
import App from './App'
import router2 from './router'

/* eslint-disable no-new */

new Vue({
  el: '#app',
  components: {App},
  template: '<App/>',
  router: router2
})
View Code

猜你喜欢

转载自www.cnblogs.com/infaaf/p/9688760.html