Vue.jsルーティングマネージャVue Routerについて話します。

10324 ワード

スタートをきる
HTML

<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>Hello App!</h1>
 <p>
  <!--    router-link      . -->
  <!--      `to`       . -->
  <!-- <router-link>           `<a>`    -->
  <router-link to="/foo">Go to Foo</router-link>
  <router-link to="/bar">Go to Bar</router-link>
 </p>
 <!--      -->
 <!--                n    -->
 <router-view></router-view>
</div>

JavaScript

// 0.            ,  Vue VueRouter,    Vue.use(VueRouter)

// 1.    (  )   。
//         import   
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2.     
//             。   "component"    
//    Vue.extend()         ,
//   ,          。
//            。
const routes = [
 { path: '/foo', component: Foo },
 { path: '/bar', component: Bar }
]

// 3.    router   ,    `routes`   
//            ,          。
const router = new VueRouter({
 routes // (  )     routes: routes
})

// 4.         。
//       router         ,
//              
const app = new Vue({
 router
}).$mount('#app')

//   ,       !
ルータを注入することによって、私達はあらゆるコンポーネントの中でthis.$routerを通じてルータにアクセスすることができます。また、this.$routeを通じて現在のルートにアクセスすることもできます。

export default {
 computed: {
  username () {
   //          `params`    
   return this.$route.params.username
  }
 },
 methods: {
  goBack () {
   window.history.length > 1
    ? this.$router.go(-1)
    : this.$router.push('/')
  }
 }
}
routesオプション(Aray)
リダイレクト

//    /a    /b
const router = new VueRouter({
 routes: [
  { path: '/a', redirect: '/b' }
 ]
})
//                 :
const router = new VueRouter({
 routes: [
  { path: '/a', redirect: { name: 'foo' }}
 ]
})
//       ,         :
const router = new VueRouter({
 routes: [
  { path: '/a', redirect: to => {
   //               
   // return           /    
  }}
 ]
})
ルート名

export default [
  {
    path:'/',
    redirect:'/app' //      
  },
  {
    path: '/app',
    //    ,     
    name: 'app',
  }
]

//     
<router-link :to="{name:'app'}">app</router-link>
ルート要素情報
ルートを定義するときは、metaフィールドを設定できます。

export default [
  {
    path:'/',
    redirect:'/app' //      
  },
  {
    path: '/app',
    //**   HTML meta  **
    meta: {
      title: 'this is app',
      description: 'asdasd'
    },
  }
]
入れ子ルート

export default [
  {
    path:'/',
    redirect:'/app' //      
  },
  {
    path: '/app',
    //       /app/test
     children: [
      {
       path: 'test',
       component: Login
      }
     ]
  }
]
ルートコンポーネントの参照

export default [
  {
    path:'/',
    redirect:'/app' //      
  },
  {
    path: '/app/:id', // /app/xxx ,        $route.params.id     
    //   :       props     Todozhong  
    //    
    props: true,
    //    
    props:{id:456}
    //    
    props: (route) => ({ id: route.query.b }),
    component: Todo,

  }
]

modeオプション(string)
vue-routerデフォルトhashモード――URLのhashを使って一つの完全なURLをシミュレーションするので、URLが変更されると、ページは再ロードされない。
丑いhashを望まないなら、経路のhistoryモードを利用して、history.pusState APIを十分に利用してURLのジャンプを完成します。ページを再ロードする必要はありません。

const router = new VueRouter({
 mode: 'history',
 routes: [...]
})
このようなモードで遊ぶには、バックグラウンドのサポートが必要です。
ベース(string)
適用されたベースパス。例えば、1ページのアプリケーションサービスが/app/下にあれば、ベースは「/app/」に設定されるべきです。

return new Router({
  routes,
  mode: 'history',//    hash#
  base: '/base/', // path      /base/,   
 })
linkActive Class(string)
デフォルト値:「router-link-active」
グローバルプロファイルのデフォルトは「クラス名のアクティブ化」です。

return new Router({
  routes,
  mode: 'history',//    hash#
  base: '/base/', // path      /base/,   
  //   calss  
  linkActiveClass: 'active-link', //         
  linkExactActiveClass: 'exact-active-link',//    
 })
linkExact Active Class(string)
デフォルト値:「router-link-exact-active」
グローバル設定が正確に起動するデフォルトのクラス。
scrollBehavior(Function)
ルートがジャンプしたらスクロールしますか?

export default () => {
 return new Router({
  routes,
  mode: 'history',//    hash#
  base: '/base/', // path      /base/,   
  //          
  /*
    to:    ,      
    from:    
    savedPosition:       
  */
  scrollBehavior (to, from, savedPosition) {
   if (savedPosition) {
    return savedPosition
   } else {
    return { x: 0, y: 0 }
   }
  },
 })
}
parseQuery/strigifyQuery(Function)

/  import      router,         router
export default () => {
 return new Router({
  routes,
  mode: 'history',//    hash#
  base: '/base/', // path      /base/,   
  //        ?a=2&b=3,string->object
   parseQuery (query) {

   },
   //object->string
  stringifyQuery (obj) {

   }
 })
}

fallback(bollan)
ブラウザがhistory.pusState制御ルートをサポートしていない場合、hashモードに戻るべきですか?デフォルトはtrueです。
falseに設定すると、ジャンプしてページを更新し、複数ページのアプリケーションに相当します。
<router-link>
過渡的効果
は基本的なダイナミックコンポーネントですので、コンポーネントで移行効果を追加できます。

<transition>
 <router-view></router-view>
</transition>
高級な使い方
名前付きビュー

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

const router = new VueRouter({
 routes: [
  {
   path: '/',
   components: {
   //    
    default: Foo,
    //    
    a: Bar,
    b: Baz
   }
  }
 ]
})

ナビゲーションガード
全体を守る

import Vue from 'vue'
import VueRouter from 'vue-router'

import App from './app.vue'

import './assets/styles/global.styl'
// const root = document.createElement('div')
// document.body.appendChild(root)
import createRouter from './config/router'
Vue.use(VueRouter)

const router = createRouter()

//       (  )

//           
router.beforeEach((to, from, next) => {
  console.log('before each invoked')
  next()
//  if (to.fullPath === '/app') {
//   next({ path: '/login' })
//   console.log('to.fullPath :'+to.fullPath )

//  } else {
//   next()
//  }
})

router.beforeResolve((to, from, next) => {
  console.log('before resolve invoked')
  next()
})

//        
router.afterEach((to, from) => {
  console.log('after each invoked')
})

new Vue({
  router,
  render: (h) => h(App)
}).$mount("#root")

ルート独享の守備
ルート構成において、before Enterガードを直接定義することができます。

export default [
  {
    path:'/',
    redirect:'/app' //      
  },
  {
 
    path: '/app',
    //          
    beforeEnter(to, from, next) {
      console.log('app route before enter')
      next()
    }
    component: Todo,
  }
]
ユニット内のガード

export default {
 //    
 beforeRouteEnter(to, from, next) {
  //  ! !       `this`
  //         ,         
  console.log("todo before enter", this); //todo before enter undefined
  //           next       。             ,                。
  next(vm => {
    //    `vm`       
   console.log("after enter vm.id is ", vm.id);
  });
 },
 //     
 beforeRouteUpdate(to, from, next) {
  console.log("todo update enter");
  next();
 },
 //     
 beforeRouteLeave(to, from, next) {
  console.log("todo leave enter");
  const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
   if (answer) {
    next()
   } else {
    //    next(false)    。
    next(false)
   }
 },
 props:['id'],
 components: {
  Item,
  Tabs
 },
 mounted() {
  console.log(this.id)
 },
};
ロード怠惰
参考:ロード怠惰
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。