前言
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。Vue Router 通过定义路由映射表,将 URL 和组件映射关联起来,实现了页面的跳转和组件的切换
使用步骤
- 安装 Vue Router:可以通过 npm 或者 yarn 安装,引入js文件
- 创建路由实例:通过 VueRouter 构造函数创建一个路由实例。
- 配置路由映射表:在路由实例中配置路由映射表,将 URL 和组件映射关联起来。
- 注册路由实例:将路由实例挂载到vue实例
- 使用路由:在组件中使用路由,通过 router-link 组件实现页面跳转,通过 router-view 组件实现组件切换。
vue代码实例
步骤一:引入js文件
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 引入js文件 -->
<script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
步骤二:创建路由实例
const router = new VueRouter({
// 路由的重定向
// 3.创建映射关系
routes: [
{
path: '/',
redirect: '/index'
},
{
path: '/index',
component: index
},
{
path: '/detail',
component: detail
},
{
path: '/main/:ids',
component: main,
name: 'my'
},
]
})
步骤三:创建映射关系
routes: [
{
path: '/',
redirect: '/index'
},
{
path: '/index',
component: index
},
{
path: '/detail',
component: detail
},
{
path: '/main/:ids',
component: main,
name: 'my'
},
]
步骤四:将路由实例挂载到vue实例
const vm = new Vue({
// 4.将路由实例挂载到vue实例
router,
el: '#app',
data: {
},
methods: {
}
})
步骤五:使用路由
html部分
<div id='app'>
<!-- 5.预留展示区 -->
<router-view></router-view>
</div>
<template id="index">
<div>
首页
<!-- 跳转 -->
<a href="#/detail?courseid=123">去详情页a</a>
<router-link to="/detail">去详情页</router-link>
<!-- 声明式的路由传参 -->
<router-link :to="{path:'/detail',query:{courseid:123,id:456} }">去详情页1</router-link>
<router-link :to="{name:'my',params:{ids:789} }">去个人中心</router-link>
<!-- 必须传参 -->
<!-- <router-link :to="{name:'my'}">去个人中心1</router-link> -->
<!-- 函数式的路由传参 -->
<button @click="toDetail">toDetail</button>
<button @click="toMine">toMine</button>
</div>
</template>
<template id="detail">
<div>
详情页
</div>
</template>
<template id="main">
<div>
个人中心
</div>
</template>
script部分
let index = {
template: '#index',
methods: {
toDetail() {
console.log(1);
// this.$router.push('/detail')
this.$router.push({
path: '/detail',
query: {
id: 123
}
})
},
toMine() {
this.$router.push({
name: 'my',
params: {
ids: 45644
}
})
},
}
}
let detail = {
template: '#detail',
created() {
console.log(this);
console.log(this.$route.query);
console.log(this.$route.query.courseid);
}
}
let main = {
template: '#main',
created() {
console.log(this);
console.log(this.$route.params.ids);
}
}
总结
Vue路由可以让我们在单页应用(SPA)中实现页面之间的切换,而不需要每次都重新加载整个页面。Vue路由可以帮助我们构建更加流畅、快速的用户体验,同时也可以提高应用程序的性能。
Vue路由的主要作用是将不同的页面组件映射到不同的URL路径上,当用户访问某个URL时,路由会根据URL匹配对应的组件,并将其渲染到页面上。Vue路由还可以实现路由参数传递、路由拦截、路由嵌套等功能,使得我们可以更加灵活地控制页面的展示和交互。
总之,Vue路由是Vue.js框架中非常重要的一部分,它可以帮助我们构建高效、灵活、可扩展的单页应用。