vue router 基本语法

1、引入相关的js文件

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

2、

let home = {
        template:'<div>首页</div>',
        created(){
            console.log(this.$route.query)
        }
    }
    let user = {
        template:'<div>用户中心</div>'
    }

    let routes = [  //路由和组件的映射表
        {path:'/home',name:'homelink',component:home},
        {path:'/user',name:'userlink',component:user},
        //redirect  重定向
        {path:'*',redirect:'/home'}
    ];

    //实例化路由对象
    let router = new VueRouter({
        routes
    })

    let vm = new Vue({
        el:'#app',
        router
    })

3、router-link 组件的属性,tag 改变组件在页面中的种类,to 指定跳转的地址

<div id="app">
    <router-link :to="{path:'/home',query:{a:1}}" tag="button">首页</router-link>
    <router-link :to="{name:'userlink'}" tag="button">用户中心</router-link>
    <router-view></router-view>
</div>

4、动态路由

let home = {
        template:'<div>首页</div>',
        created(){
            console.log(this.$route.query)
        }
    }

    let routes = [  //路由和组件的映射表
        {path:'/home/:id',name:'homelink',component:home},
    ];

    //实例化路由对象
    let router = new VueRouter({
        routes
    })

    let vm = new Vue({
        el:'#app',
        router
    })
<div id="app">
    <!--<router-link :to="{path:'/home',params:{id:1}}" tag="button">首页</router-link>-->
    <router-link :to="{name:'homelink',params:{id:1}}" tag="button">首页</router-link>
    <router-view></router-view>
</div>

动态路由必须使用name才生效,不能用path

posted @ 2019-05-05 10:43  冰冰~  阅读(272)  评论(0编辑  收藏  举报