之三 命名路由和命名视图

命名路由和命名视图

    给路由定义不同的名字,根据名字进行匹配

    给不同的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!

扫描二维码关注公众号,回复: 4808578 查看本文章

猜你喜欢

转载自blog.csdn.net/purple_lumpy/article/details/85935771