1、简介
传统的Web应用程序不同页面间的跳转都是向服务器发起请求,服务器处理请求后向浏览器推送页面。在单页应用程序中,不同视图(组件的模板)的内容都是在同一个页面中渲染,页面间的跳转都是在浏览器端完成,这就需要用到前端路由。在Vue.js中,可以使用官方的路由管理器Vue Router。 Vue Router需要单独下载,可以使用CDN方式应用Vue Router
<script src="https://unpkg.com/vue-router@next"></script>
如果使用模块化开发,则使用npm安装方式,执行以下命令安装Vue Router。
npm install vue-router@next --save
提示:安装Vue Router时,要安装支持Vue3.0的新版本Vue Router,即这里的vue-router@next。支持vue2.0的Vue Router的版本名是vue-router。
2、HTML页面使用路由
前端路由的配置有固定的步骤。 (1)使用router-link组件设置导航链接
<router-link to="/">主页</router-link>
<router-link to="/news">新闻</router-link>
<router-link to="/books">图书</router-link>
<router-link to="/videos">视频</router-link>
to属性指定链接的URL,<router-link> 默认会被渲染为一个<a> 标签。 (2)指定组件在何处渲染,这是通过<router-view> 指定的。
<router-view></router-view>
(3)定义路由组件。
const Home={template:'<div>主页面</div>'}
const News={template:'<div>新闻页面</div>'}
const Books={template:'<div>图书页面</div>'}
const Videos={template:'<div>视频页面</div>'}
这里只是为了演示前端路由的基本用法,所以组件定义很简单。 (4)定义路由,将第(1)步设置的链接URL和组件对应起来。
const routes=[
{path:'/',component:Home},
{path:'/news',component:News},
{path:'/books',component:Books},
{path:'/videos',component:Videos}
]
(5)创建VueRouter实例,将第(4)步定义的路由配置作为选项传递进去。
const router=VueRouter.createRouter({
history:VueRouter.createWebHashHistory(),
routes
})
(6)调用应用程序实例的use()方法,传入第(5)步创建的router对象,从而让整个应用程序具备路由功能。
const app=Vue.createApp({})
app.use(router)
app.mount('#app')
完整代码如下所示。 routers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<p>
<router-link to="/">主页</router-link>
<router-link to="/news">新闻</router-link>
<router-link to="/books">图书</router-link>
<router-link to="/videos">视频</router-link>
</p>
<router-view></router-view>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/vue-router@next"></script>
<script>
const Home={template:'<div>主页面</div>'}
const News={template:'<div>新闻页面</div>'}
const Books={template:'<div>图书页面</div>'}
const Videos={template:'<div>视频页面</div>'}
const routes=[
{path:'/',component:Home},
{path:'/news',component:News},
{path:'/books',component:Books},
{path:'/videos',component:Videos}
]
const router=VueRouter.createRouter({
history:VueRouter.createWebHashHistory(),
routes
})
const app=Vue.createApp({})
app.use(router)
app.mount('#app')
</script>
</body>
</html>
任意单击某个链接之后的渲染结果: 在创建router实例时,为选项history指定的是VueRouter.createWebHashHistory(),也就是hash模式,即使用URL的hash(即URL中的锚部分,从"#"开始的部分)模拟完整的URL,以便在URL更改时不会重新加载页面。
一般我们都是模块化开发路由的,见下一篇文章。 Vue模块化开发使用路由
|