作用
通过模块化拆分页面,避免重复代码,方便于代码维护。
介绍
在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')