张蕾的技术博客

vue学习大纲5-vue-router详解

2017-06-17  本文已影响376人  cd72c1240b33

首先下载vue-router,命令: npm i vue-router --save-dev

基本路由5步走:

1、创建vueRouter实例,并进行配置

var Home={//单独把Home组件拎出来
    template:'<h1>home</h1>'
};
var List={template:'<h1>list</h1>'}
var router=new VueRouter({
    routes:[
        {path:'/home',component:Home},
        {path:'/list',component:List},
        {path:'/',component:Home},//默认路由指向
        {path:'*',component:Home} //404页面的设置
    ]
})

2、把配置好的router实例,放入new Vue的实例中;

var vm=new Vue({
    router,//2:把router声明到vue实例上
    el:'#app'
})

3、添加路由跳转,通过 <router-link to="/home"></router-link>

<router-link to="/home">首页</router-link>
<router-link to="/list">列表页</router-link>

4、显示组件 <router-view></router-view>
5、设置默认路由和404页面--已经在上面路由设置那里进行设置;

配置字路由 children

var Home={template:`#home`}; //通过template创建的home模版;
var router=new VueRouter({
        routes:[
            {path:'/home',component:Home,//这里我把Home提取了
                children:[
                    //这里注意:千万不能写成"/path",否则就不执行了;
                    {path:'login',component:{
                        template:'<p>登录</p>'
                    }},
                    {path:'reg',component:{
                        template:'<p>注册</p>'
                    }}
                ]
            }
        ]
    });

vue2路由中的查询参数

var router=new VueRouter({
    routes:[
        {path:'/list',component:List,
            children:[
            //通过":"设置默认模糊路由;
                {path:'news/:id',component:{
                //通过{{$route.params.id}}来获取路由参数
                    template:`<h3>文章{{$route.params.id}}</h3>`
                }}
            ]
        },
        {path:'*',component:Home}
    ]
});
{path:'/list',component:List,
    children:[
        {path:'news/:id',
            //JS中获取路由参数,用beforeEnter,他有三个参数:to,from,next
            beforeEnter(to,from,next){
                //console.log(to.params.id)
                next();//这个中间件,往下走才能看到显示的组件
            },
            component:{
            template:`<h3>文章{{$route.params.id}}</h3>`
        }}
    ]
}
上一篇 下一篇

猜你喜欢

热点阅读