1.安装路由 npm install vue-router --save
2.路由文件的配置
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/home',
component: () => import("../views/Home.vue"), //懒加载方式引入组件
}
]
const router = new VueRouter({
routes
})
export default router
3.路由跳转
(1)router-link:
<template>
<div id="app">
this is app
<router-link to="/home">home</router-link>
<router-view></router-view>
</div>
</template>
(2)编程式导航:
<template>
<div id="app">
this is app
<button @click="toHome">home</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
methods: {
toHome() {
this.$router.push({ path: "/home"}); //置于$router栈中
}
}
};
</script>
4.动态路由:
例:将路由配置中path改为:
path: '/home/:id'
可以通过以下方法将url中的id值进行输出
<h3>{{ $route.params.id }}</h3>
5.嵌套组件:
const routes = [
{
path: '/home/:id',
component: () => import("../views/Home.vue"),
//嵌套组件
children: [{
path: '/child',
component: () => import("../views/child.vue")
}]
}
]
Home.vue
<template>
<div>
This is home!
<h3>{{ $route.params.id }}</h3>
<!--嵌套组件显示 -->
<router-view></router-view>
</div>
</template>