vue路由總結


      vue-router, vue自帶的路由,下面是一些簡單的操作說明:

      一、安裝

         1、cnpm install vue-router --save  命令進行安裝

         2、在main.js或者使用vue-router的地方,通過import 來導入import vRouter from 'vue-router'

         3、Vue.use(vRouter )

         4、開始配置路由

               

 1 import Vue from 'vue'
 2 import App from './App'
 3 import VRouter from 'vue-router'
 4 import Apple from './components/apple'
 5 import Banana from './components/banana'
 6 import Redapple from './components/redapple'
 7 //使用vue.use來注冊使用VRouter插件
 8 Vue.use(VRouter);
 9 //這樣VRouter作為一個類來使用,我們自己實例化這樣的一個類
10 let router = new VRouter({
11     mode: 'history',
12    routes: [
13      {
14         path: '/apple/:color',//為頁面設置路由參數
15         component: Apple,
16         //路由嵌套
17         children: [
18             {
19               path: 'redapple',
20               component: Redapple               注意:在路徑上加上‘/’表示從根目錄開始跳轉 21                                                      不加‘/’表示從當前頁面進行跳轉  
23             },
{
path:'/redapple',
component: Redapple
}
24 ] 25 }, 26 { 27 path: '/banana', 28 component: Banana 29 } 30 ] 31 }); 32 /* eslint-disable no-new */ 33 new Vue({ 34 el: '#app', 35 router,//將這樣的router放到根目錄里面 36 // es6 通過render方法來使用外部引入的App組件 37 render: h => h(App) 38 })

    二、常用的路由方式

      1、常規的路由    

 1 var routes = [
 2     {
 3         path:"/one",
 4 
 5         component: a
 6     },
 7     {
 8         path:"/two",
 9         component: b
10     },
11 ]

 

       2、嵌套路由

 1    routes: [
 2 13      {
 3 14         path: '/apple',
 4 15         component: Apple,
 5 16         //路由嵌套
 6 17         children: [
 7 18             {
 8 19               path: 'redapple',
 9 20               component: Redapple               注意:在路徑上加上‘/’表示從根目錄開始跳轉
10 21                                                      不加‘/’表示從當前頁面進行跳轉  
11 23             },
12                {
13                  path:'/redapple',
14                  component: Redapple
15                }
16 24         ]

    

    3、動態路由,一般適用於詳情頁

1 {
2     path:"/two:id",
3     component: b
4 }

 

     4、路由跳轉的方式與傳參,適合寫入一些方法中:

        a、 router.push(location)

 1  //  字符串
 2    router.push('home')
 3  
 4  //  對象
 5     router.push({path: 'home'})
 6  
 7  //  命名的路由
 8     router.push({ name: 'user',  params: { userId: 123 }})
 9 
10  // 帶查詢參數,變成 /register?plan=private
11     router.push ({ path: 'register', query: { plan: 'private' }})

     

     b、標簽跳轉,其中傳參的方式和上面的一樣

1 <router-link :to="{ name: 'one'}">User</router-link>
2 <router-link :to="{ name: 'two'}">User</router-link>

 

  5、路由的重定向

       重定向(Redirect)就是通過各種方法將各種網絡請求重新定個方向轉到其它位置,用於網站調整或網頁被移到一個新地址,它也是通過routes配置來完成,下面例子是從/a 重定向到 /b, 如果a 找不到,直接跳到b:

1 var router = new VueRouter({
2   routes: [
3     { path: '/a', redirect: '/b' }
4   ]
5 })

 

   6、路由的別名

        /a 的別名是 /b,意味着,當用戶訪問 /b 時,URL 會保持為 /b,但是路由匹配則為 /a,就像用戶訪問 /a 一樣。簡單的說就是給 /a 起了一個外號叫做 /b ,但是本質上還是 /a。適合頁面的推廣:

1 var router = new VueRouter({
2   routes: [
3     { path: '/a', component: A, alias: '/b' }
4   ]
5 })

 

    7、路由中props傳遞

1     {
2       path: '/personal/:id',
3       name: 'personal',
4       component: personal,
5       props: true     // 這一步非常重要
6     }

 

 

   頁面中會直接被渲染出來

 

 三、常用的路由方法

       1、返回上一頁, 一個全局的goBack 事件

1 Router.prototype.goBack = function() {
2   window.history.go(-1)
3 }

     

1 // 在瀏覽器記錄中前進一步,等同於 history.forward()
2  
3    router.go(1)
4 
5 // 后退一步記錄,等同於 history.back()
6 
7     router.go(-1)

// 前進 3步記錄
router.go(3)

// 如果history 記錄不夠用, 那就默默地的失敗唄
router.go(-100)
router.go(100)

 

  2、router.replace()      

        類型: boolean
         默認值: false
         設置 replace 屬性的話,當點擊時,會調用 router.replace() 而不是 router.push(),於是導航后不會留下 history 記錄。即使點擊返回按鈕也不會回到這個頁面。
            /加上replace: true后,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄。

1   this.$router.push({path: '/home', replace: true})
2     //如果是聲明式就是像下面這樣寫:
3    <router-link :to="..." replace></router-link>
4     // 編程式:
5     router.replace(...)

 

   3、需要先跳轉到登錄的頁面

     

    

    將登錄收的token存在localstory中。

   

     4、路由過渡效果(App.vue)

  1 <template>
  2   <div id="app" class="app">
  3     <transition :name='transitionName'>
  4      <router-view class="child-view"></router-view>
  5     </transition>
  6   </div>
  7 </template>
  8 
  9 <script>
 10 export default {
 11   name: 'app',
 12   data () {
 13     return {
 14       data: 'abcd',
 15       info: 'nono',
 16       transitionName: 'slide-left'
 17     }
 18   },
 19  watch: {
 20 '$route' (to, from) {
 21  const toDepth = to.path.split('/').length
 22 const fromDepth = from.path.split('/').length
 23 this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
 24  }
 25  },
// 判斷左右滑動
26 beforeCreate () { 27 console.log('創建前……') 28 console.log(this.data) 29 console.log(this.$el) 30 }, 31 // created () { 32 // console.log('已創建……') 33 // console.log(this.info) 34 // console.log(this.data) 35 // }, 36 // beforeMount () { 37 // console.log('mounted之前……') 38 // console.log(this.info) 39 // console.log(this.$el) 40 // }, 41 // mounted () { 42 // console.log('mounted……') 43 // console.log(this.info) 44 // console.log(this.$el) 45 // }, 46 // beforeUpdate () { 47 // console.log('更新前========') 48 // }, 49 // updated () { 50 // console.log('更新完成') 51 // }, 52 // beforeDestroy () { 53 // console.log('銷毀前……') 54 // console.log(this.info) 55 // console.log(this.$el) 56 // }, 57 destroyed () { 58 console.log('已銷毀……') 59 console.log(this.info) 60 console.log(this.$el) 61 }, 62 beforeRouteUpdate (to, from, next) { 63 let isBack = this.$router.isBack 64 if (isBack) { 65 this.transitionName = 'slide-right' 66 } else { 67 this.transitionName = 'slide-left' 68 } 69 this.$router.isBack = false 70 } 71 } 72 </script> 73 74 <style> 75 @import "./common/css/reset.css"; 76 .app { 77 font-family: 'Avenir', Helvetica, Arial, sans-serif; 78 -webkit-font-smoothing: antialiased; 79 -moz-osx-font-smoothing: grayscale; 80 text-align: center; 81 color: #000; 82 font-size:.14rem; 83 height:2rem; 84 } 85 .child-view { 86 position: absolute; 87 width:100%; 88 transition: all .8s cubic-bezier(.55,0,.1,1); 89 } 90 .slide-left-enter, .slide-right-leave-active { 91 opacity: 0; 92 -webkit-transform: translate(50px, 0); 93 transform: translate(50px, 0); 94 } 95 96 .slide-left-leave-active, .slide-right-enter { 97 opacity: 0; 98 -webkit-transform: translate(-50px, 0); 99 transform: translate(-50px, 0); 100 } 101 </style>

 

5、 路由的封裝

 1 import Vue from 'vue'
 2 import Router from 'vue-router'
 3 import {storage} from '../assets/js/utils/storage'
 4 import routeConfig from './route.config.json';
 5 var registerRoute = (routeConfig) => {
 6   let route = [];
 7   routeConfig.map(pages => {
 8     route.push({
 9       path: pages.path,
10       name: pages.name !== undefined ? pages.name : null,
11       redirect: pages.redirect !== undefined ? pages.redirect : null,
12       component: require(`@/pages${pages.component}`).default,
13       meta: pages.meta !== undefined ? pages.meta : null,
14       children: pages.children !== undefined ? registerRoute(pages.children) : null
15     })
16   });
17 
18   return route;
19 };
20 
21 var route = registerRoute(routeConfig);
22 
23 Vue.use(Router)
24 
25 Router.prototype.goBack = function() {
26   this.isBack = true
27   window.history.go(-1)
28 }
29 
30 const routeInstance = new Router({
31   routes: route
32 })
33 
34 routeInstance.beforeEach((to, from, next) => {
35   if (to.path !== '/') {
36     let familyId = storage.cookie.get('familyId');
37     if ((familyId !== null)) {
38       next()
39     } else {
40       routeInstance.replace({path: '/'})
41     }
42   }
43   next()
44 })
45 
46 export default routeInstance

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM