什么是路由
路由分为后端路由和前端路由。
后端路由:对于普通的网站,所有的超链接都是URL地址,所有的VUE地址都对应服务器上对应的资源,也就是不同url地址对应不同的静态资源。
前端路由:对于单页面应用程序来说,主要通过URL中的hash(#号)来实现不同页面之间的切换,同时,hash有一个特点:HTTP请求中不会包含hash相关的内容;所以,单页面程序中的页面跳转主要用hash实现;在单页面应用程序中,这种通过hash改变来切换页面的方式,称作前端路由(区别于后端路由)。
如何使用路由
第一步:引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法);
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>//vue
<script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>//路由
第二步:创建路由new VueRouter(),接受的参数是一个对象
const router = new VueRouter()
第三步:在实例化的对象里配置属性routes:[],这个数组里的对象包含path属性和component属性,path属性是url的地址,component属性就是显示的组件(传组件的对象)(以下均以index,user两个组件为例)
<template id="index">
<div>
index
<router-view></router-view>
</div>
</template>
<template id="user">
<div>
user
</div>
</template>
<script>
let index = {
template: "#index"
};
let user = {
template: "#user"
};
const router = new VueRouter({
routes: [
{
path: "/index",
component: index,
},
{
path:"/user",
component:user,
},
]
})
</script>
第四步:将路由挂载到Vue实例中
const vm = new Vue({
el: '#app',
data: {
},
methods: {
},
router,
})
第五步:展示区域
<div id='app'>
<router-view></router-view>
</div>
此时,在浏览器打开,在/目录下展示index实例,在/user目录下展示user实例。
模板如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.0.0/dist/vue-router.js"></script>
</head>
<body>
<!-- vue实例控制区域 -->
<div id='app'>
<!-- 展示区域 -->
<router-view></router-view>
</div>
<!-- index组件 -->
<template id="index">
<div>
index
</div>
</template>
<!-- user组件 -->
<template id="user">
<div>
user
</div>
</template>
<script>
let index = {
template: "#index"
};
let user = {
template: "#user"
}
// 路由实例
const router = new VueRouter({
routes: [
//创建映射关系
{
path: "/",
component: index,
},
{
path:"/user",
component:user,
},
]
})
// vue实例
const vm = new Vue({
el: '#app',
data: {
},
methods: {
},
router,
})
</script>
</body>
</html>