图解Vue嵌套路由router-view

作用

通过模块化拆分页面,避免重复代码,方便于代码维护。

介绍

在App.vue里放一个ChildContainer模版容器,router-link控制ChildTemplate展示的内容,见下图。
图解

介绍

使用路由前先安装:npm install vue-router

示例代码

放在app.vue里的代码

<template>
  <div id="app">
    <p >
      <router-link to="/parent/param1" >RouterView默认模式</router-link><br/>
      <router-link to="/parent/param2/child1" >RouterView带一个param2参数</router-link><br/>
      <router-link to="/parent/param3/child2" >RouterView带一个param3参数</router-link><br/>
    </p>
    <router-view></router-view>
  </div>
</template>

<script>


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

放在mian.js里的代码

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'

Vue.config.productionTip = false

Vue.use(VueRouter)

const ChildContainer = {
  template: `
    <div class="container">
      <h2>接受参数: {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

const ChildTemplate1 = { template: '<div>子页面router-view 1</div>' }
const ChildTemplate2 = { template: '<div>子页面router-view 2</div>' }
const ChildTemplate3 = { template: '<div>子页面router-view 3</div>' }

const router = new VueRouter({
  routes: [
    { path: '/parent/:id', component: ChildContainer,
      children: [
        // ChildTemplate1 将会展示在 Parent的 <router-view>里
        // 当 /parent/:id 被匹配
        { path: '', component: ChildTemplate1 },
				
        // ChildTemplate2 将会展示在 Parent的 <router-view>里
        // 当 /parent/:id/child1 被匹配
        { path: 'child1', component: ChildTemplate2 },

        // ChildTemplate3 将会展示在 Parent的 <router-view>里
        // 当 /parent/:id/child2 被匹配
        { path: 'child2', component: ChildTemplate3 }
      ]
    }
  ]
})

new Vue({
  render: h => h(App),
  router
}).$mount('#app')
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值