Vue中一級路由的配置

一、引入vue-router.js庫javascript

二、建立路由所需的模塊(組件):html

  • 使用Vue.extand()方法建立模塊(組件),是在分寫的時候使用;合寫的代碼以下,直接在component→template內寫組件
  • 分配路由路徑
    //合寫
    <script>
        var vm=new Vue({
            el:'#box',
            data:{},
            //添加路由的配置項
            //router:路由對象(實例)
            //router:new VueRouter()
    
            //設置路由對象的配置項
            /*new VueRouter({
                路徑信息:路徑信息盛放在數組中
                routes:[
                    {path:'分配的url路徑',component:'組件名'}
                ]
            })
            */
            router:new VueRouter({
                routes:[
                    {path:'/home',component:{
                        template:'<h2>首頁</h2>'
                    }},
                    {path:'/news',component:{
                        template:'<h2>新聞</h2>'
                    }},
                    {path:'/hot',component:{
                        template:'<h2>熱點</h2>'
                    }},
                ]
            })
        })
    </script>
    //分寫,相對經常使用
    <script>
        //一、準備路由所需的模塊(組件)
        //全局Vue下,有extend(),用來註冊路由所需的模塊(組件)
        var Home=Vue.extend({
            template:'#home'
        });
    
        var News=Vue.extend({
            template:'#news'
        });
    
        var Hot=Vue.extend({
            template:'#hot'
        });
    
        var arr=[
            {path:'/home',component:Home},
            {path:'/news',component:News},
            {path:'/hot',component:Hot}
        ];
    
        var router=new VueRouter({
            routes: arr
        });
    
        var vm=new Vue({
            el:'#box',
            data:{},
            router:router
        })
    
        //路由重定向
        //push():路由對象自帶方法,進行路由跳轉push('url')
        router.push('/home')
    </script>

     

三、更改HTML結構vue

  • 使用<router-link></router-link>標籤代替HTML的<a></a>標籤,to屬性用來設置路由跳轉的地址
  • 使用<router-view></router-view>來佔位展現
    <div id="box">
            <ul>
                <li><router-link to='/home'>home</router-link></li>
                <li><router-link to='/news'>news</router-link></li>
                <li><router-link to='/hot'>hot</router-link></li>
            </ul>
    
            <div class="show">
                <router-view></router-view>
            </div>
        </div>

    效果以下(分別是點擊了home和news以後的效果)java

四、路由的重定向,做用是在刷新以後從新定向到一個模塊(組件/URL)上去vue-router

  • 在分寫的時候,直接用router的push('url')
    //即爲上面路由配置的合寫代碼中最下面的寫法
    //路由重定向push():路由對象自帶方法,進行路由跳轉push('url')
        router.push('/home')

     

  • 合寫的時候要寫在鉤子函數內,使用$router.push('url')
    beforeCrate:function(){
        this.$router.push('/home')
    }
相關文章
相關標籤/搜索