vue-routerの基本的な使い方

2098 ワード

  • 1.スタートnpm install--save vue-routerプロジェクトで使用する場合、以下の方法で
  • import Vue from 'vue'
    import VueRouter from 'vue-router'
    //   Vue   VueRouter   
    Vue.use(VueRouter)
    //    ,    
    new VueRouter({
        //...
    })
    
  • 2.ルーティングマッピング
  • //router-link       
    //to           
    to home
    

    レンダリングされます
    to home
    
  • 3.経路出口
  • //              
    
    
  • 4.ルーティングコンポーネントを定義するには、まず明確にします.一般的に、ルーティングにはコンポーネントがマッピングされます.
  • const routes = [
        path: '/',
        component: require('./app.vue'),
        //         app.vue    router-view  
        children: [
            {
                path: '/',
                component: require('./home.vue')
            },
            {
                path: '/questions',
                component: require('./questions.vue'),
                name: 'questions', //     
                //     
                meta: {
                        correctNum: 0
                   }
            },
            {
                path: 'score',
                   component: require('../page/score'),
                   name: 'score',
                //     ,            
                   beforeEnter (to, from, next) {
                        to.meta.correctNum = from.meta.correctNum
                        next()
                   }
            }
        ]
    ]
    
    const router = new VueRouter({
        mode: 'history',
        base: __dirname,
        routes
    })
    
    new Vue({
        //...
        router
    })
    

    上記のルーティング構成は次のように対応しています.
    //app.vue 
    

    最上位レベルのルーティングは、最上位レベルの出口であるindexにマッピングされる.html内
    
        

    以上、vue-routerの基本的な使い方ですが、私も小さなdemoを作りました.詳しくはGithubを参照してください.
    間違いがあれば指摘を歓迎します.転載は出典を明記してください!