我们初始化我们的Vue项目后,打开工程目录src/router下的index.js。我们可以把工程默认的helloworld.vue文件名,以及组件名更改。同样也需要在index.js文件中更改引入的文件名和组件名。
/*index.js 需要更改的地方*/
import Home from '@/components/pages/home/Home'
Vue.use(Router) //这里是全局路由配置
export default new Router({
mode: 'history',
routes: [{
path: '/',
name: 'Home',
component: Home
}]
})
这里面的routes是指所有的路由,默认情况下,也就是不加mode:history的情况,打开浏览器显示的地址会是,localhost:8080/#/home,mode: 'history’的作用就是去掉“#”符号。需要添加路由 时,我们只需要再在routes添加组件即可,不要忘记引入Vue文件哈。
import Home from '@/components/pages/home/Home'
import Roll from '@/components/pages/roll/Roll'
export default new Router({
mode: 'history',
routes: [{
path: '/',
name: 'Home',
component: Home
},
{
path: '/',
name: 'Roll',
component: Roll
}]
})
当我们需要跳转页面时,我们只需要在触发跳转的外层添加router-link标签,此处用法为Vue2.0.
<router-link to="/Roll" class="tag_item" >
<div class="img img2"></div>
</router-link>
当我们需要打开二级标题,或者页面有切换的tab栏时,我们就可以配置二级路由。同样的引入组件的方法,我们把组件引入到index.js 中。
import Home from '@/components/pages/home/Home'
import Roll from '@/components/pages/roll/Roll'
import zhengzaijinxin from '@/components/pages/roll/components/zhengzaijinxin'
import wocanyude from '@/components/pages/roll/components/wocanyude'
import yijieshu from '@/components/pages/roll/components/yijieshu'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [{
path: '/',
name: 'Home',
component: Home
},
{
path: '/roll',
name: 'Roll',
component: Roll,
redirect: '/Roll/zhengzaijinxin',
children: [{
path: '/Roll/zhengzaijinxin',
name: 'zhengzaijinxin',
component: zhengzaijinxin
},
{
path: '/Roll/wocanyude',
name: 'wocanyude',
component: wocanyude
},
{
path: '/Roll/yijieshu',
name: 'yijieshu',
component: yijieshu
}
]
},
这个时候路由已经配置好了,但我们打开页面却发现没有二级路由的页面,那是因为我们没有设置路由出口,在roll页面上加上router-view标签就好啦。
<div class="tab-item">
<router-link :to="{ path: '/Roll/yijieshu' }" >
<div class="world"></div>
</router-link>
</div>
</div>
<router-view></router-view>
</div>
当我们需要设置默认显示的页面时只需要添加 redirect即可。
path: '/roll',
name: 'Roll',
component: Roll,
redirect: '/Roll/zhengzaijinxin',
那是因为我们在配置路由时书写不规范,我们需要在路径前加上一级路由。
{
path: '/roll',
name: 'Roll',
component: Roll,
redirect: '/Roll/zhengzaijinxin',
children: [{
path: '/Roll/zhengzaijinxin',
name: 'zhengzaijinxin',
component: zhengzaijinxin
},
{
path: '/Roll/wocanyude',
name: 'wocanyude',
component: wocanyude
},
{
path: '/Roll/yijieshu',
name: 'yijieshu',
component: yijieshu
}
]
},
router-link也是一样的
<router-link :to="{ path: '/Roll/yijieshu' }" >