1. 程式人生 > >之三 命名路由和命名檢視

之三 命名路由和命名檢視

命名路由和命名檢視

    給路由定義不同的名字,根據名字進行匹配

    給不同的router-view 定義名字,通過名字進行對應元件的渲染

我們舉例如下。

首先,命名路由。

如下是GoodList.vue

<template>
  <div>
    這是商品列表頁
    <span>{{$route.params.goodsId}}</span>
    <br />
    <span>{{$route.params.name}}</span>
    <router-link to="/goods/title">顯示商品標題</router-link>
    <router-link to="/goods/image">顯示商品圖片</router-link>
    <div>
      <router-view></router-view>
    </div>
    <router-link v-bind:to="{name:'Cart',params:{cartId:123}}">跳轉到購物車</router-link>
  </div>
</template>

router/index.js 中命名的Cart,如下。

import Vue from 'vue'
import Router from 'vue-router'
import GoodList from '@/views/GoodList'
import Title from '@/views/Title'
import Image from '@/views/Image'
import Cart from '@/views/Cart'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/goods',
      name: 'GoodList',
      component: GoodList,
      children: [
        {
          path: 'title',
          name: 'Title',
          component: Title
        }, {
          path: 'image',
          name: 'Image',
          component: Image
        }
      ]
    }, {
      path: '/cart/:cartId',
      name: 'Cart',
      component: Cart
    }
  ]
})

然後,命名檢視。即給router-view 加name 值。

我們在App.vue 中加兩個檢視,如下。

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
    <router-view name="title"></router-view>
    <router-view name="image"></router-view>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

然後在router/index.js 中修改,如下。

import Vue from 'vue'
import Router from 'vue-router'
import GoodList from '@/views/GoodList'
import Title from '@/views/Title'
import Image from '@/views/Image'
import Cart from '@/views/Cart'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/goods',
      name: 'GoodList',
      components: {
        default: GoodList,
        title: Title,
        image: Image
      }
    }, {
      path: '/cart/:cartId',
      name: 'Cart',
      component: Cart
    }
  ]
})

Done!