Vue2.x中舍弃了1.x中<a>标签的用法,而是通过<router-link></router-link>标签来实现路由相关的功能。
<router-link> 是一个组件,该组件用于设置一个导航链接,切换不同 HTML 内容。 to 属性为目标地址, 即要显示的内容。
导入相关文件
<script src="vue.js"></script>
<script src="vue-router.js"></script>
建立路由主体
<div id="box">
<router-link :to='"home"'>主页</router-link>
<router-link to='/news'>新闻页</router-link>
<router-link to='/games'>游戏页</router-link>
<router-view></router-view>
</div>
创建模板(也可以从外部引入参考组件相关知识)
var Home={
template:'<h3>该页面为首页</h3>'
}
var News={
template:'<h3>该页面为新闻页</h3>'
}
var Games={
template:'<h3>该页面为游戏页</h3>'
}
配置路由
var routes=[
{path:'/home',component:Home},
{path:'/news',component:News},
{path:'/games',component:Games},
//指定默认页面
{path:'/',redirect:'/home'}
]
生成路由
var router=new VueRouter({routes})
指定作用域
new Vue({
router,
el:'#box'
})
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>路由搭建配置</title>
<script src="vue.js"></script>
<script src="vue-router.js"></script>
</head>
<body>
<div id="box">
<router-link :to='"home"'>主页</router-link>
<router-link to='/news'>新闻页</router-link>
<router-link to='/games'>游戏页</router-link>
<router-view></router-view>
</div>
<script>
//创建模板
var Home={
template:'<h3>该页面为首页</h3>'
}
var News={
template:'<h3>该页面为新闻页</h3>'
}
var Games={
template:'<h3>该页面为游戏页</h3>'
}
//配置路由
var routes=[
{path:'/home',component:Home},
{path:'/news',component:News},
{path:'/games',component:Games},
//指定默认页面
{path:'/',redirect:'/home'}
]
//生成路由
var router=new VueRouter({
routes
})
new Vue({
router,
el:'#box'
})
</script>
</body>
</html>
运行结果(点击标签可以实现简单的单页切换功能)