Vue 路由管理

133 阅读1分钟

文章目录

Vue 路由管理

官网描述

官网 : router.vuejs.org/zh/
在这里插入图片描述

其实说白了就是原先我们是用a标签进行页面跳转

使用vue中路由后,在注册组件之后,我们在页面中使用进行配置,用法与标签一样。然后跳转到的页面内容,由标签渲染出来。

例子:

根组件( 使用路由)

<!--根组件-->

<template>
  <div id="app1">
    <h2>基本路由1</h2>
    <div>
      <div>
        <!--      路由切换-->
        <router-link to="/about" class="class-router">about</router-link>
        <router-link to="/home" class="class-router"> home</router-link>
      </div>
      <!--    需要现实的路由界面-->
      <div>
        <router-view> </router-view>
      </div>

    </div>

  </div>


</template>

<script>

export default {
}
</script>

<style>
</style>

注册两个路由组件

About.vue

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

</template>

<script>
  export default {
  }
</script>

<style>
</style>

Home.vue

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

<script>
  export default {
  }
</script>

<style scoped>
div{
  color: red;
}
</style>

注册路由管理器

index.js


/**
 路由器模块
 **/

//引入Vue 和 路由插件
import Vue from 'vue'
import VueRouter from 'vue-router'



//引入路由组件
import About from '../pages/About'
import Home from '../pages/Home'

//调用路由器
Vue.use(VueRouter)

//向外暴露路由器对象
export default new VueRouter({
//n个路由

  routes:[
  {
    path:"/about",
    component:About
  },
  {
    path:"/home",
    component:Home
  },
  //默认请求
  {
    //根路径
    path:'/',
    redirect:'/about'
  }
]

})

入口main函数



/*
    入口js: 创建Vue实例
 */
//引入路由器
import router from './router'



new Vue({
// 配置路由器
  router
})

项目结构

在这里插入图片描述

可能遇到问题

<router-view> </router-view> 内容不显示 无法跳转到路径对应的路由界面中

原因是: 设置路由器是 routes 而不是 routers

结果如图

在这里插入图片描述

在这里插入图片描述