vue-router

2017-12-21  本文已影响0人  candy252324

示例代码地址

1.动态路由

“路径参数”使用冒号 : 标记, 如/goods/:goodsId/user/:goodsName。当匹配到一个路由时,参数值会被设置到 this.$route.params

<body>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

  <div id=app>   
    <router-link to="/goods/89/user/candy">link1</router-link>
    <router-link to="/goods/90/user/hank">link2</router-link>
    <router-view></router-view>
  </div>

  <script>
  // GoodsList 中通过$route.params拿到参数
    const GoodsList = { template:
    `
      <div>
        <p>goodsId: {{$route.params.goodsId}}</p>
        <p>goodsName:{{$route.params.goodsName}}</p>
      </div> 
    `}  

    const routes = [{         
      path:'/goods/:goodsId/user/:goodsName',   // goodsId和goodsName是路由的参数而非页面跳转的参数
      name: 'GoodsList',
      component: GoodsList   
    }]

    const router = new VueRouter({
      routes 
    })

    const app = new Vue({
      router,
      // $route 表示当前路由
      watch:{
        $route(val,old){
          console.log(val)
        }
      }
    }).$mount('#app')
  </script>
</body>
动态路由.png

2.嵌套路由

嵌套路由使用children

const routes = [
    {         
      path:'/goods',   
      name: 'GoodsList',
      component: GoodsList,
      children:[
        {
          path:'title',     // 二级路由,注意这里不能写'/title','/title'是一级路由
          name:'title',
          component:Title
        },
        {
          path:'image',    
          name:'image',
          component:Image
        },
      ] 
    },
    {
      path:'/cart',    //一级路由
      name:'cart',
      component:Cart
   }]

GoodsList 中的<router-view>是装二级路由的容器

const GoodsList = { template: `
  <div>
    商品列表页面
    <br>
    <router-link to="/goods/title">显示商品标题</router-link>   
    <router-link to="/goods/image">显示商品图片</router-link>
    <router-link to="/cart">显示购物车</router-link>
    <router-view></router-view>      
  </div>
`}  
嵌套路由.png

3.编程式路由

this.$router.push方法可接收路径字符串,也可接收对象,也可接收带参数的对象,接收带参数的对象时,传递的参数可在目标路由页面中通过$route.query来获取

// js
this.$router.push({path:'/cart?cartId=123'}) 
// html
<div>购物车:{{$route.query.cartId}}</div>

4.命名路由和命名视图

有时候想同时 (同级) 展示多个视图,而不是嵌套展示,这时候就需要用到命名路由和命名视图。

<div id="app">
  <router-view></router-view>   <!--用于显示默认视图-->
  <router-view name="title2"></router-view>
  <router-view name="title3"></router-view>
</div>

命名路由的方式需要传递一个对象,使用v-bind:

const Title1 = { template: `
  <div>          
    <router-link v-bind:to='{name:"cart",params:{cartId:123}}'>title1</router-link>
  </div>
` };
const routes = [{
  path: "/",
  components: {
    default: Title1,   // 默认视图
    title2: Title2,
    title3: Title3
  }
},{
  path:'/cart/:cartId',
  name:'cart',
  component:Cart,
}];

如下图所示,Title1Title2, Title3三个视图同时显示:

命名路由和命名视图.png
上一篇下一篇

猜你喜欢

热点阅读