什么是路由
路由就是URL地址,地址不同,则显示的页面内容不同,路由分为前端路由和后端路由,Vue属于前端框架,因此我们讲解的路由也是前端路由。
Vue是单页面应用程序,通过hash(#)来实现不同页面之间的切换。
什么是单页面应用程序?通俗地讲就是不需要刷新页面,所有组件都在一个页面上的应用程序。
使用路由
在页面中使用路由需要以下5个步骤。
(1)引入路由。
(2)创建路由实例对象。
(3)为构造函数传递配置对象。
路由匹配规则的属性是routes,其值是数组,后期每一个匹配规则就是一个对象
path是哈希后面的路径,component是路径对应的组件
(4)将路由挂载到Vue实例对象。
(5)视图层显示组件内容。
src\router\index.js
import Vue from 'vue'
import Router from 'vue-router' // (1)引入路由
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
// (2)创建路由实例对象
export default new Router({
// (3)为构造函数传递配置对象
routes: [
// {
// path: '/',
// redirect: 'login'
// },
{
path: '/',
components: {
'header': {
template: '<div>头部</div>',
},
'main': {
template: '<div>主体</div>',
},
'footer': {
template: '<div>底部</div>',
}
}
},
{
path: '/login',
component: () => import('@/views/test/Login'),
},
{
path: '/register/:id',
component: () => import('@/views/test/Register'),
},
{
path: '/user',
component: () => import('@/views/test/User'),
children: [{
path: 'login',
component: () => import('@/views/test/Login'),
},
{
path: 'register/:id',
component: () => import('@/views/test/Register'),
}
]
}
]
})
src\App.vue
<template>
<div id="app">
<a href="#/login">登录</a>
<a href="#/register">注册</a>
<router-link to="/" tag="span">HOME</router-link>
<router-link to="/login?id=1" tag="span">登录</router-link>
<router-link to="/register/1">注册</router-link>
<router-link to="/user">用户</router-link>
<!-- (5)视图层显示组件内容 -->
<transition>
<router-view></router-view>
</transition>
<router-view name="header"></router-view>
<router-view name="main"></router-view>
<router-view name="footer"></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;
}
.router-link-active {
color: red;
}
.v-enter,
.v-leave-to {
opacity: 0;
transform: translateX(200px);
}
.v-enter-active,
.v-leave-active {
transition: all 1s ease;
}
</style>
src\views\test\User.vue
<template>
<span>
<p><router-link to="/user/login?id=1">登录</router-link></p>
<p><router-link to="/user/register/1">注册</router-link></p>
<p><button @click="click1">链式路由跳转</button></p>
<transition>
<router-view></router-view>
</transition>
</span>
</template>
<script>
export default {
name: 'User',
data() {
return {}
},
created() {},
methods: {
click1() {
this.$router.push({
path: "/login",
query: {
id: 2
}
})
}
}
}
</script>
<style>
</style>
官方文档: https://v3.router.vuejs.org/zh/guide/
书籍: Vue.js核心技术解析与uni-app跨平台实战开发 第6章 Vue.js路由