vue2.0路由进阶

一、路由的模式

  第一种用history方式实现,HTML5使用window.history.pushState()实现路由的切换而不刷新页面。

  第二种使用hash值的方式来实现。

  vue2.0两种都可以使用只需要在配置路由时加上

  mode:'history/mode'    vue2.0默认为hash模式。需要切换为history模式时使用

  

  const router = new VueRouter({
  // mode:'history',
  routes:routes
  })

  两种模式的区别:

  hash:支持所有浏览器,包括不支持HTML5的浏览器。

  history:依赖html5 history API

二、一般配置路由:

  

  <div>
    <router-link to="/home">主页</router-link>
    <router-link to="/news">新闻</router-link>
  </div>
  <div>
    <router-view></router-view>
  </div>

  //准备组件
  var Home={
  template:'<h3>我是主页</h3>'
  };
  const News={
  template:'<h3>我是新闻</h3>'
  };
  //配置路由
  const routes=[
  {path:'/home',component:Home},
  {path:'/news',component:News},
  {path:'*',redirect:'/home'}
  ];
  //生成路由实例
  const router = new VueRouter({
  routes:routes
  });
  //最后挂载
  new Vue({
  router:router,
  el:'#box'
  })

这样有一个缺点:如果修改路由配置的路径时每一个router-link都需要改变,所以有如下优化方法:

  html中:

    <router-link :to="{name:'Home'}">              //有冒号,传入的为一个对象

  JS中:

    配置路由时使用

      routes:[

        {name:'Home',path:'/',component:Home},

      ]

    需要改变路径时只需要改变配置时的路径即可。

三、路由使用tag标签

  例如有些时候在ul中必须嵌套li要设置路由的话必须在li中再嵌套<router-link>

  eg:

           <ul>

      <li><router-link></router-link></li>  

    </ul>

  使用tag标签时即可优化:

    <ul>

      <router-link tag="li"></router-link>

    </ul>

四、动态路由

  eg:

  <router-link :to="{name:'BookDetails',params:{id:1}}"></router-link>   

  在JS中使用

  const bookID = this.$router.params.id调用即可