一 、安装
npm install vue-router 选择下载版本方法@3
二 、创建组件
如果在一个项目中使用它 ,必须通过 Vue.use()明确安装路由功能,用vue-cli生产了项目结构,src文件目录下会有一个router文件夹,此处就是用来编写路由组件的地方。在scr/router/index.js,这个文件解释路由的核心文件:
import Vue from 'vue' //引入Vue
import Router from 'vue-router' //引入vue-router
import Hello from '@/components/Hello' //引入根目录下的Hello.vue组件
Vue.use(Router) //Vue全局使用Router
export default new Router({
routes: [ //配置路由,这里是个数组
{ //每一个链接都是一个对象
path: '/', //链接路径
name: 'Hello', //路由名称,
component: Hello //对应的组件模板
},{
path:'/hi',
component:Hi,
children:[ //子路由,嵌套路由 (此处偷个懒,免得单独再列一点)
{path:'/',component:Hi},
{path:'hi1',component:Hi1},
{path:'hi2',component:Hi2},
]
}
]
})
三、router-view 用于主页面展示跳转页面
四、router-link 和 go 标签点击跳转使用方法
1.语法:<router-link tag="li" active-class="active" to="/xinwen"></router-link>
tag="要转换的标签"
to="跳转的子路径"
2.语法:<li @click="go('/xinwen')"></li>
直接使用标签添加事件@click="go('/xinwen')"
go('跳转路径')
五、创建导航项目
1.主页面
html:
<template>
<div id="app">
<ul>
<router-link tag="li" active-class="active" to="/xinwen">新闻</router-link>
<router-link tag="li" active-class="active" to="/tiyu">体育</router-link>
<router-link tag="li" active-class="active" to="/guoji">国际</router-link>
<li @click="go('/xinwen')">新闻</li>
<li @click="go('/guoji')">国际</li>
</ul>
<router-view>
</router-view>
</div>
</template>
css:
<style>
div {
margin: 0 auto;
width: 680px;
}
ul {
float: left;
margin-bottom: 100px;
}
li {
width: 200px;
height: 40px;
list-style: none;
float: left;
line-height: 40px;
margin-right: 10px;
text-align: center;
background: linear-gradient(skyblue, pink);
}
*{
margin: 0;
padding: 0;
}
.active {
background: greenyellow;
color: aliceblue;
}
</style>
js是go方法的页面跳转
<script>
export default {
data(){
return {
tabIndex:0
}
},
methods:{
go(url){
this.$router.push(url)
}
}
}
</script>
跳转页面一
跳转页面二
跳转页面三
终端接口
路由搭建