Vue中简单的路由实现

简单路由实现

cnpm install vue-router -S or yarn add vue-router -S

  1. 引入vue-router,如果是在脚手架中,引入VueRouter之后,需要通过Vue.use来注册插件

    router/index.js文件

    import Vue from 'vue'
    import Router from 'vue-router'
    Vue.use(Router)  
  1. 创建router路由器
    new Router({
      routes:[
        {path:"/home",component:Home}
      ]
    })
  1. 创建路由表并配置在路由器中
    var routes = [
        {path,component}//path为路径,component为路径对应的路由组件
    ]

    var router = new Router({
        routes
    })
    
    export default router
  1. 在根实例里注入router,目的是为了让所有的组件里都能通过this. r o u t e r 、 t h i s . router、this. routerthis.route来使用路由的相关功能api
    import router from "./router"
    new Vue({
      el: '#app',
      router,  //注册一下  让组件可以通过this.$router or this.$route 使用路由相关的api属性或方法
      template: '<App/>',
      components: { App }
    })
  1. 利用router-view来指定路由切换的位置

  2. 使用router-link来创建切换的工具,会渲染成a标签,添加to属性来设置要更改的path信息,且会根据当前路由的变化为a标签添加对应的router-link-active/router-link-exact-active(完全匹配成功)类名

<router-link to="/main">main</router-link>
<router-link to="/news">news</router-link>

.router-link-active{
    color:red;
}
原文地址:https://www.cnblogs.com/Mine-/p/14098618.html