Vue中一级路由的配置

1、引入vue-router.js库

2、创建路由所需的模块(组件):

  • 使用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>
        //1、准备路由所需的模块(组件)
        //全局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>

3、更改HTML结构

  • 使用<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之后的效果)

4、路由的重定向,作用是在刷新之后重新定向到一个模块(组件/URL)上去

  • 在分写的时候,直接用router的push('url')
    //即为上面路由配置的合写代码中最下面的写法
    //路由重定向push():路由对象自带方法,进行路由跳转push('url')
        router.push('/home')
  • 合写的时候要写在钩子函数内,使用$router.push('url')
    beforeCrate:function(){
        this.$router.push('/home')
    }

猜你喜欢

转载自my.oschina.net/u/3648322/blog/1809828