vuejs仿美团,饿了么项目之——路由篇
2018-07-26 本文已影响430人
从小就很瘦
最近做了一个高效还原美团的vue项目,今天把项目中主要的一些功能抽离出来做个小demo。方便学习。这篇博客主要介绍路由的配置。
- vue-cli脚手架的webpack-simple模板来搭建
vue init webpack-simple vue-demo
cd vue-demo
npm install
npm run dev
- 入口文件中配置下路由。首先要安装vue-router
npm install vue-router --save
main.js中引入路由模块并配置路由。这里我写了个简单的header组件,nav组件,nav组件通过router-link链接到good组件,seller组件,rating组件。
import Vue from 'vue'
import App from './App.vue'
import vueRouter from 'vue-router'
import Good from './good/good.vue'
import Shop from './shop/shop.vue'
import Rating from './rating/rating.vue'
Vue.use(vueRouter)
const routes = [
{
path:'/',
redirect:'/good'
},
{
path:'/good',
name:'Good',
component: Good
},
{
path:'/shop',
name: 'Shop',
component: Shop
},
{
path: '/rating',
name: 'Rating',
component: Rating
}
]
const router = new vueRouter({
routes,
mode: 'history',
linkActiveClass: 'active'
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
- nav组件中配置router-link,并在根组件中插入router-view,将3个组件渲染到这里。
nav组件中,router-link通过 v-bind:to绑定到各个组件。
<template>
<div class="nav">
<router-link :to="{name: 'Good'}" class="nav-item">商品</router-link>
<router-link :to="{name: 'Shop'}" class="nav-item">店家</router-link>
<router-link :to="{name: 'Rating'}" class="nav-item">评论</router-link>
<i class="line"></i>
</div>
</template>
<style>
.nav {
display: flex;
width: 100%;
height: 40px;
line-height: 40px;
border-bottom: 1px solid #ccc;
position: relative;
}
.nav-item {
flex: 1;
width: 33.3%;
text-decoration: none;
text-align: center;
color: #666;
}
.active {
color: #ffbb22;
}
.line {
position: absolute;
height: 2px;
width: 33.3%;
background: #ffbb22;
bottom:0;
transition: .3s all
}
.nav-item.active:nth-child(2)~.line {
transform: translateX(100%);
}
.nav-item.active:nth-child(3)~.line {
transform: translateX(200%);
}
</style>
App.vue中,加上keep-alive是为了在切换路由中将状态保留在内存中,防止重复渲染DOM。
<template>
<div id="app">
<Header></Header>
<Nav></Nav>
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
import Header from './header/header.vue'
import Nav from './nav/nav.vue'
export default {
components: {
Header,
Nav,
}
}
</script>
路由就到此为止,下一篇写一下关于如何获取数据。