Vue技術點整理-Vue Router

路由 Vue Routercss

對於單頁面應用來講,若是涉及到多個頁面的話,就必需要使用到路由,通常使用官方支持的 vue-router

一,Vue Router 在項目中的安裝引用html

1,在頁面中使用<script>快速使用Vue Router開發vue

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>使用script直接引入Vue Router</title>
    </head>
    <body>
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
        <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
        <div id="app">
          <h1>頁面共同header</h1>
          <p>
            <router-link to="/first">頁面1</router-link>
            <router-link to="/second">頁面2</router-link>
          </p>
          <router-view></router-view>
        </div>
        <script>
            
            //template也能夠使用import從外部引入進來
            const first = { template: '<div>I am first</div>' }
            const second = { template: '<div>I am second</div>' }
            const routes = [
              { path: '/first', component: first },
              { path: '/second', component: second }
            ]
            const router = new VueRouter({
              routes
            })
            const app = new Vue({
              router
            }).$mount('#app')
        </script>
    </body>
</html>
View Code

2,在vue cli框架使用路由vue-router

app.js編程

<template>
  <div id="app">
      <router-view></router-view>
  </div>
</template>
View Code

main.js瀏覽器

import Vue from "vue";
import App from "./App.vue";
import router from "./router.js";
Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");
View Code

router.js緩存

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const routes = [
        {
            path: '/index',
            name: 'index',
            component: () => import("@/views/index.vue"),
        },
        {
            path: '/login',
            name: 'login',
            component: () => import("@/views/login.vue"),
        },
        {
            path: '/fansNumber',
            name: 'fansNumber',
            component: () => import("@/views/fansNumber.vue"),
        }
];

routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '');
});
const router = new Router({ routes });
router.beforeEach((to, from, next) => {
  //路由執行以前,處理一些邏輯
  next();
})
export default router;
View Code

 二,Vue Router 基礎功能用法app

1,router-路徑式傳參框架

//路由定義 router.js
const router = new VueRouter({
  routes: [
    // 動態路徑參數 以冒號開頭
    { path: '/user/:id', component: User }
  ]
})

//第一種編程式跳轉指定路由 test.vue
const userId = '123'
this.$router.push({ 
  path: '/user/' + userId
})
//第二種編程式跳轉指定路由 test.vue
this.$router.push({ 
  name: 'user',
  params: userId
})
//聲明式跳轉指定路由 test.vue 
<router-link to="/user/{{userId}}"> 
  <span>跳轉</span> 
</router-link> 

//在user的js裏面接收參數 
created() { 
  console.info(this.$route.params.userId) 
}

注:你能夠在一個路由中設置多段『路徑參數』,對應的值都會設置到 $route.params 中。例如:異步

模式 匹配路徑 $route.params
/user/:username /user/jack { username:'jack' }
/user/:username/pwd:password /user/jack/pwd/123 { username:'jack',pwd:123

 

 

 

 

 2,router-get方式傳參

//路由定義 router.js
const router = new VueRouter({
  routes: [
    { path: '/user', component: User }
  ]
})

//編程式跳轉到指定路由 test.vue
this.$router.push({
name: "user",
query: {
    userName: 'jack'
    pwd: '123'
}
});
//在user的js裏面接收參數 
created() { 
  console.info(this.$router.query.userName) 
  console.info(this.$router.query.pwd) 
}

 3,編程式導航

  •   router.replace() 和 router.push() 同樣的用法,區別爲:
  •   router.push() 每次調用,都會往history裏面添加一條新紀錄,能夠返回歷史頁面
  •   router.replace() 每次調用,不會往history裏面添加記錄,而是會替換掉當前的history記錄,沒有歷史記錄
  •   router.go(1)  //瀏覽器中,向前進一步,等同於history.foward()
  •   router.go(-1) //瀏覽器中,向後一步,等同於history.back()

 4,基於路由的動態過渡效果

<template>
  <div id="app">
    <transition name="fade">
      <router-view></router-view>
    </transition>
  </div>
</template>
<style lang="scss">
.fade-enter-active{
  transition: opacity .6s;
}
.fade-enter{
  opacity: .5;
}</style>

5,導航守衛,過濾器

const router = new VueRouter({
  routes: [
    {
      path: "/home",
      name: "Home",
      component: Home,
      meta: {
        type: '1',
        title: '首頁'
      }
    }
  ]
});

//路由執行前
router.beforeEach((to, from, next) => {
  //校驗token是否過時
  if(to.token && Util.checkToken(to.token)){
     return next({path: to.path});
   }else{
     return next({path: '/login'});
   }
   //使用路由自定義meta,統一處理title
   const title = to.meta && to.meta.title;
   if (title) {
     document.title = title;
   }
})
//路由執行後
router.afterEach((to) => {
    //恢復頁面滾動位置
    window.scrollTo(0, 0);
});

export default router;

6,使用scrollBehavior中的異步滾動

const router = new Router({
  scrollBehavior(to, from, savedPosition) {
    // keep-alive 返回緩存頁面後記錄瀏覽位置
    if (savedPosition && to.meta.keepAlive) {
      return savedPosition;
    }
    // 異步滾動操做
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ x: 0, y: 1 });
      }, 0);
    });
  },
});

 

更多功能,請參考router官網

相關文章
相關標籤/搜索