我们开始建的项目时没有router的项目。
所以现在需要建立router文件夹,index.js文件,做路由跳转配置。
我在components下建立了,HelloWorld.vue、Hi.vue、nav.vue。
首先在App.vue下引入nav.vue.使用没有router的引入方式。参考
import Nav from '@/components/nav' //引入页面
components:{ //使用组件nav
Nav
}
<Nav/> //html中显示
HelloWorld.vue、Hi.vue内容随便写。
nav.vue中代码,应该都能看懂吧!html js css 。router-link路由跳转
<template lang="html">
<div class="nav">
<ul>
<router-link tag="li" to="/hello">hello</router-link>
<router-link tag="li" to="/hi">hi</router-link>
</ul>
</div>
</template>
<script>
export default {};
</script>
<style lang="css">
.nav{
width:100%;
height: 50px;
line-height: 50px;
background:#FFF;
}
.nav ul {
clear: both;
overflow: hidden;
}
.nav li {
float: left;
margin:0 20px;
list-style:none;
}
</style>
index.js中代码
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Hi from '@/components/Hi'
Vue.use(Router)
export default new Router({ //路由跳转 和nav中router-link对应
routes: [
{
path: '/hello',
component: HelloWorld,
},
{
path: '/hi',
component: Hi
}
]
})
main.js中代码如下
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
这样是把所有关于路由跳转的配置都放在了index.js中了。
路由重定向,放在index.js的router下面,当请求路径为空的时候自动跳转到hello路径下。
{
path: '/',
redirect:'/hello'
},
路由的嵌套。
新建几个页面。建一个pages文件夹,下面建hello1.vue hello2.vue ,在HelloWorld中定义router-link显示路径。要写全
<div class="hello">
HelloWorld:
<ul>
<li><router-link to="/hello/Hello1">H1</router-link></li> //定向路径要写全
<li><router-link to="/hello/Hello2">H2</router-link></li>
</ul>
<router-view></router-view> //显示返回的页面h1orh2
</div>
建立路由在index.js中
引入,路由定向,代码如下。
import Hello1 from '@/pages/hello1'
import Hello2 from '@/pages/hello2'
//因为是在hello下写的嵌套,路由定向写在他的内部
{
path: '/hello',
component: HelloWorld,
redirect:'/hello/hello1', //重定向,路径要写全。好好体会写全是什么意思
children:[ //嵌套路由
{
path:'hello1',
component:Hello1
},
{
path:"hello2",
component:Hello2
}
]
},
这样子嵌套就完成了。
小知识
路由标签开始显示颜色在App.vue中写css样式
a:link,a:hover,a:active,a:visited{
/* 标签显示颜色 */
color:#222;
}
如何让路由标签鼠标点击到就变颜色
//nav.vue中
.active{
color:red !important;
}
//index.js 中routers方法中
linkActiveClass:"active", //点中出现效果,对应nav中的active设置
mode:'history', //路由跳转有个历史记录