隨着vue越來越火,而vue-router卻是一個項目不可或缺的,所以在這里結合實例總結一下router的用法,也是給自己的一個總結。
1、首先第一步當然是安裝vue-router依賴,當然也可直接script引用。接着新建一個router文件下新建一個index.js,這個文件主要用於配置路由。index.js代碼如下:
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const Recommend = () => import('components/recommend/recommend') const Rank = () => import('components/rank/rank') const Search = () => import('components/search/search') const SingerDetail = () => import('components/singer-detail/singer-detail') const TopList = () => import('components/top-list/top-list') export default new Router({ routes: [ { path: '/', redirect: '/recommend' }, { path: '/rank', component: Rank, children: [ { path: ':id', component: TopList } ] }, { path: '/search', component: Search, children: [ { path: ':id', component: SingerDetail } ] } ] })
我相信看過官網的都大概明白上面代碼的意思,path:’/’意思是默認指定的路由路徑,也就是剛進去指定的路由,這里默認指向recommend;而每個children代表子路由,比如Search這個組件的子路由是SingerDetail,當然可以指定三級、四級路由。
2、第二步就是在main.js文件下引入router這個文件,並初始化。代碼如下:
import Vue from 'vue'; import App from './App'; import router from './router'; new Vue({ el: '#app', router, render: h => h(App) });
3、第三步在App.vue這個文件下定義一個容器用於展示路由指定下的組件。代碼如下:
<template> <div id="app" @touchmove.prevent> <div class="tab"> <router-link tag="div" to="/recommend"> <span class="tab-link">推薦</span> </router-link> <router-link tag="div" to="/rank"> <span class="tab-link">排行</span> </router-link> <router-link tag="div" to="/search"> <span class="tab-link">搜索</span> </router-link> </div> <keep-alive> <router-view></router-view> </keep-alive> </div> </template>
<router-view></router-view>就是路由容器,之所以放在keep-alive這個標簽下是對數據進行緩存,這樣用戶每次返回列表的時候,都能從緩存中快速渲染,而不是重新渲染。To=”/recommend”表示點擊”推薦”這個標簽就跳轉到recommend這個路由,也就是我們之前配置的路徑。
講到這里我們已經簡單的完成一個單頁面應用了。這里我采用的是模塊化編程。我把路由配置、初始化、渲染寫在各個文件下。這樣也符合大家的組件化開發思路。下面我在進行一些路由用法的補充。
4、多級路由的用法
<template> <div class="recommend"> <ul> <li @click="selectItem(item)" v-for="item in discList" class="item"> item.text </li> </ul> <router-view></router-view> </div> </template> <script type="text/ecmascript-6"> export default { data() { return { discList: [ {dissid:1,text:'條目1'}, {dissid:2,text:'條目2'}, {dissid:2,text:'條目2'} ], } } methods: { selectItem(item) { this.$router.push({ path: `/recommend/${item.dissid}` }) } } } </script>
在這里我通過在recommend這個組件下實現二級路由跳轉。首先渲染discList列表里面的數據,點擊li標簽跳轉到第一步在index.js定義的Recommend組件下的子路由Disc。通過$router.push()這個方法,帶上這條數據的唯一id值即可實現子路由跳轉。
router.push()方法就是用來動態導航到不同的鏈接的。它會向history棧添加一個新的記錄,點擊<router-link :to="...">等同於調用router.push(...)。
5、router.go()的用法
router.go(n)
這個方法的參數是一個整數,意思是在 history 記錄中向前或者后退多少步,類似 window.history.go(n)。
例子
// 在瀏覽器記錄中前進一步,等同於 history.forward()
router.go(1)
// 后退一步記錄,等同於 history.back()
router.go(-1)
// 前進 3 步記錄
router.go(3)
// 如果 history 記錄不夠用,那就默默地失敗唄
router.go(-100)
router.go(100)