現在的項目都以模塊化的方式去開發,所以在這樣的開發模式下,如何更好的去管理路由是開發中所需要考慮的重點,幸運的是當前的開發中已經有了成熟的中間件去管理,我們只需要用就可以了
下面是我在學習vue-router的時候在原來基礎上修改出來的demo,也是爲了有助於對vue-router的理解
首先理解下vue官網的一個示例demo
https://jsfiddle.net/yyx990803/xgrjzsup/
這裏展示的是完成一個路由所必須的基礎步驟,由於這裏不是模塊化的開發模式,下面就是一個簡單的demo使用模塊化開發
github:https://github.com/chrisvfritz/vue-2.0-simple-routing-example
這裏首先提供一個叫page.js的三方包去管理路由,將大幅度簡化原有代碼的書寫比例,鏈接如下:
page.js:https://github.com/visionmedia/page.js
使用page後的代碼簡化:https://github.com/chrisvfritz/vue-2.0-simple-routing-example/compare/master...pagejs
可以拉下來自己測試下,在原來的基礎上我想去使用vue-router,這裏因爲個人原因代碼無法上傳github,所以只能列出來代碼防止以後忘記,便於複習
首先是文件的目錄樹
首先是 main.js,這裏綁定了路由的文件,掛載了路由組件顯示的位置
import Vue from 'vue'
import VueRouter from 'vue-router'
import routerConfig from '../src/routes.js'
import appHome from './pages/appHome.vue'
Vue.use(VueRouter)
const router = new VueRouter({
routes:routerConfig
})
const app = new Vue({
router,
render:h=>h(appHome)
}).$mount('#app');
apphome:這裏是主路由頁面,裏面定義了兩個路由和一個展示路由組件的位置
<template>
<div>
<p>
<router-link to="/home">Home</router-link>
<router-link to="/home/about">/home/About</router-link>
</p>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:'appHome',
}
</script>
router.js:定義路由地址和組件的綁定關係,這裏加載佈局有層級關係(即通過路由一層層的去加載佈局組件),也是佈局組件加載到每一個組件的主要部分
import Home from './pages/Home.vue'
import About from './pages/About.vue'
import MainLayout from "../src/layouts/Main.vue";
import notFound from './pages/404.vue'
const routerConfig=[{
path: '/home', component: MainLayout,//加載佈局組件
children:[
{path:'',component:Home},
{path:'about',component:About}
]
},
{
path:'/about',component:notFound
}
]
export default routerConfig
main.vue:主要頁面佈局
<template>
<div class="container">
<ul>
<li>
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</template>
<script>
import VLink from '../components/VLink.vue'
export default {
name: 'main-view',
components: {
VLink
}
}
</script>
<style scoped>
.container {
max-width: 600px;
margin: 0 auto;
padding: 15px 30px;
background: #f9f7f5;
}
</style>
vlink.vue,這裏很雞肋,就是一個展示鏈接是否訪問的
<template>
<a
v-bind:href="href"
v-bind:class="{ active: isActive }"
>
</a>
</template>
<script>
export default {
props: {
href: {
type:String,
required: true
}
},
computed: {
isActive () {
return this.href === window.location.pathname
}
}
}
</script>
<style scoped>
.active {
color: cornflowerblue;
}
</style>
home:頁面文件,跟about頁面類似展示內容
<template>
<div>
<p>Welcome home</p>
</div>
</template>
<script>
export default {
name: 'Home',
mounted(){
console.log('is home')
}
};
</script>
大概的文件都放在上方了,使用vue-router路由的主要注意點就是如何去加載佈局組件的問題,他的事項是將路由的鏈接和組件綁定在一起,所以可以通過配置子鏈接的方式去一層層的加載組件佈局