VUE的路由器的總結


vue的路由器,我們在使用vue進行開發的時候,是必須用到的一個vue自帶的組件,下面進行vue經常的操作的一些說明

1.vue-router的安裝

在命令行里面使用 cnpm install vue-router --save命令進行安裝

在main.js或者其他使用vue-router的地方,通過import來導入  import VRouter from 'vue-router'

//使用vue.use來注冊使用VRouter插件
Vue.use(VRouter);

import Vue from 'vue'
import App from './App'
import VRouter from 'vue-router'
import Apple from './components/apple'
import Banana from './components/banana'
import Redapple from './components/redapple'
//使用vue.use來注冊使用VRouter插件
Vue.use(VRouter);
//這樣VRouter作為一個類來使用,我們自己實例化這樣的一個類
let router = new VRouter({
    mode: 'history',
   routes: [
     {
        path: '/apple/:color',//為頁面設置路由參數
        component: Apple,
        //路由嵌套
        children: [
            {
              path: 'redapple',
              component: Redapple               注意:在路徑上加上‘/’表示從根目錄開始跳轉
不加‘/’表示從當前頁面進行跳轉
} ] }, { path:
'/banana', component: Banana } ] }); /* eslint-disable no-new */ new Vue({ el: '#app', router,//將這樣的router放到根目錄里面 // es6 通過render方法來使用外部引入的App組件 render: h => h(App) })

在上面這樣使用了之后,在我們所需要的頁面進行展示

 <!-- v-router的使用 -->
     <router-view></router-view>  //展示
     <router-link :to="'apple'"> to apple</router-link> //相當於a標簽
     <router-link :to="{path:'/banana',query:{color:'yellow'}}">to banana</router-link>
     <router-link :to="{path:'apple/redapple'}">to applered</router-link>

注意:除了根據path以外,我們還可以為這個路由跳轉設置名字,也可以通過名字來進行路由的跳轉
 <router-link :to="{name:'myba'}">name router</router-link>

     {path: '/banana',
     name: 'myba',
     component: Banana}

需要特別注意的是,我們在使用v-bind進行路由的路徑的綁定的時候,有兩種方式,一個是直接以對象的方式進行綁定,類似於

<router-link :to="{path:'/banana',query:{color:'yellow'}}">to banana</router-link>
另外一種就是通過綁定字符串,但是這個字符串必須在data()里面進行設置,類似於
<router-link :to="'apple'"> to apple</router-link>
      data () {
     return {
        apple: '/apple',

       }

    } 

VUE帶參數的路由跳轉
我們在使用vue的路由器的時候,有的時候會需要傳遞參數,目前我所接觸的有兩種方式的跳轉,一個是在router的配置文件當中進行參數的配置,類似於
let router = new VRouter({
    mode: 'history',
   routes: [
     {
        path: '/apple/:color',//為頁面設置路由參數
        component: Apple,
        //路由嵌套
        children: [
            {
              path: 'redapple',
              component: Redapple
            }
        ]
     },
     {
        path: '/banana',
        component: Banana
     }
   ]
});

然后在apple.vue這個頁面通過$route.params進行獲取到所傳遞的參數

<template>
<div>
{{ msg }}
<p>{{ $route.params.color }}</p>
<button @click="getparams">get params</button>
<router-view></router-view>
<router-link :to="{path:'apple/redapple'}">to red apple</router-link>
</div>
</template>

 
         

<script>
export default {
data () {
return {
msg: 'i am apple'
}
},
methods: {
getparams () {
console.log(this.$route.params);
}
}
}

 
        

另外一種是直接在頁面當中<router-link></router-link>里面通過query進行參數的綁定
 <router-link :to="{path:'/banana',query:{color:'yellow'}}">to banana</router-link>


<template>
  <div>
    {{ msg }}
   {{$route.query.color}} <button @click="getparams">get params</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
     msg: 'i am banana'
    }
  },
  methods: {
    getparams () {
     console.log(this.$route.query.color);
    }
  }
}
</script>
他們之間的區別我認為就是一個是需要自己去在后面加上/參數,http://localhost:8080/apple/apple  
一個是點擊了之后直接在地址后面加上hash,   http://localhost:8080/banana?color=yellow(這種的比較好接受);

VUE的地址重定向
我們在網站當中往往是
http://localhost:8080訪問的是app.vue的界面,這個時候我們想讓我們的網站打開的時候,直接是apple.vue的界面,這個時候我們就用到了vue的地址重定向的功能,
我們需要在routers的配置里面加上這個就可以了
et router = new VRouter({
    mode: 'history', //去掉地址欄中默認的#hash
   routes: [
   {
    path: '/',//表示根目錄
     redirect: '/banana'  //表示你要重定向的位置
   },
{
        path: '/banana',
        component: Banana
     }
}
其他的使用方法暫時還沒有用到,后期用到了之后會更新
關於這個帶路由參數的跳轉,參考了 http://www.jb51.net/article/114432.htm


router.push(location)

http://www.jianshu.com/p/ee7ff3d1d93d

除了使用 <router-link> 創建 a 標簽來定義導航鏈接,我們還可以借助 router 的實例方法,通過編寫代碼來實現。
router.push(location)
想要導航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。

當你點擊 <router-link> 時,這個方法會在內部調用,所以說,點擊 <router-link :to="..."> 等同於調用 router.push(...)。

聲明式:<router-link :to="...">
編程式:router.push(...)
該方法的參數可以是一個字符串路徑,或者一個描述地址的對象。

// 字符串 router.push('home') // 對象 this.$router.push({path: '/login?url=' + this.$route.path}); // 命名的路由 router.push({ name: 'user', params: { userId: 123 }}) // 帶查詢參數,變成/backend/order?selected=2 this.$router.push({path: '/backend/order', query: {selected: "2"}}); // 設置查詢參數 this.$http.post('v1/user/select-stage', {stage: stage}) .then(({data: {code, content}}) => { if (code === 0) { // 對象 this.$router.push({path: '/home'}); }else if(code === 10){ // 帶查詢參數,變成/login?stage=stage this.$router.push({path: '/login', query:{stage: stage}}); } }); // 設計查詢參數對象 let queryData = {}; if (this.$route.query.stage) { queryData.stage = this.$route.query.stage; } if (this.$route.query.url) { queryData.url = this.$route.query.url; } this.$router.push({path: '/my/profile', query: queryData});

replace

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

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

綜合案例

this.$router.push({path: '/coach/' + this.$route.params.id, query: queryData});
 
        

vue2.0 $router和$route的區別

 
        

做項目的時候發現傳參數是通過 this.$route.query或者 this.$route.params接收router-link傳的參數。

在路由跳轉的時候除了用router-link標簽以外需要在script標簽在事件里面跳轉,所以有個方法就是在script標簽里面寫this.$router.push('要跳轉的路徑名'),

 在寫的時候發現這兩個為什么不同,在控制台打出this的時候,發現$route和$router同時存在

 

$route為當前router跳轉對象里面可以獲取name、path、query、params等

$router為VueRouter實例,想要導航到不同URL,則使用$router.push方法

返回上一個history也是使用$router.go方法

 

2.路由使用的部分技巧

(1)我們在路由的跳轉當中,可以使用watch來監聽路由的跳轉變化

watch: {
    changeShowType(value) {
      console.log("-----"+value);
    },
    '$route'(to,from){
      console.log(to);  //去往的界面
      console.log(from); //來自的界面
      if(to.path=="/shop/detail"){
        console.log("商品詳情");
      }
    }
  },

(2) 我們通常會在頁面當中使用到page404的界面,這個時候的路由設置為

{
path: '*',  //這個時候的路徑就是*
component: page404
}
注意:這個配置必須放置在路由表的最后,因為*代表所有的,找到*之后下面的不會再去執行了

yyzz因為在路由的配置當中不存在,所以進入的界面為預先設置好的404界面

(3)路由當中mode方式的history和hash的區別

我們知道普通的jquery的跳轉界面就是以hash的方式進行,所以每一個地址欄當中會出現默認的#號,例如

而在vue當中我們可以用history來模仿url的連接跳轉

附上  history和hsah的區別網址https://www.cnblogs.com/photon-phalanx/p/7452331.html

(3)路由鈎子函數

簡單的理解鈎子函數其實就是告訴服務器客戶端正在做什么,比如說,客戶端現在要跳轉鏈接到界面,客戶端跳轉之前,先發起請求告訴服務器我可不可以進行跳轉,這個時候服務器必須給到響應告訴客戶端說是否可以進行跳轉

路由的鈎子函數常用到的兩種形式:一個是直接寫在路由的js當中,一個是寫到要跳轉的那個vue當中

  1.直接寫在路由js當中的路由鈎子函數(直接寫在路由表里面的beforeEnter就不存在afterEnter了)

next()表示可以跳轉,不能跳轉就用next(false)

我們也可以使用next({path:'/st'})來使路由跳轉到你自定義的鏈接上去

 2.路由的鈎子函數也可以寫在我們將要跳轉的vue當中(這個時候就可以同時擁有Enter和Leave了)

 

methods: {

  },
  components: {
    headTit
  },
  beforeRouteEnter(to, from, next) {
    console.log("可不可以進行跳轉");
    next();
  },
  beforeRouteLeave(to, from, next) {
    console.log("可不可以跳走");
    next();
  }
//注意在beforeRouteLeave當中是沒有next({path})這種方式的,只有在Enter的時候才會有,但是同樣的Enter里面沒有this
要想離開的時候跳轉到別的界面,可以使用this.$router.push的方式或者進行路由判斷的形式

  beforeRouteLeave(to, from, next) {
    console.log("離開詳情");
    next();
    this.$router.push('/uououiu');
  }

  beforeRouteLeave(to, from, next) {
   console.log(to);
   if(to.path=='/shop/yyzz'){
   next({path:'/shop'});
  }
  next();
  //this.$router.push('/uououiu');
}

 

 

 

 







免責聲明!

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



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