美文网首页
vue-router配置

vue-router配置

作者: baiduo | 来源:发表于2018-04-02 10:50 被阅读0次
    • 使用方式
      • 1:下载 npm i vue-router -S
      • 2:在main.js中引入 import VueRouter from 'vue-router';
      • 3:安装插件 Vue.use(VueRouter);
      • 4:创建路由对象并配置路由规则
        • let router = new VueRouter({ routes:[ {path:'/home',component:Home} ] });
      • 5:将其路由对象传递给Vue的实例,options中
        • options中加入 router:router
      • 6:在app.vue中留坑 <router-view></router-view>

    命名路由

    • 需求,通过a标签点击,做页面数据的跳转
    • 使用router-link标签
      • 1:去哪里 <router-link to="/beijing">去北京</router-link>
      • 2:去哪里 <router-link :to="{name:'bj'}">去北京</router-link>
        • 更利于维护,如果修改了path,只修改路由配置中的path,该a标签会根据修改后的值生成href属性

    参数router-link

    • 在vue-router中,有两大对象被挂载到了实例this
    • $route(只读、具备信息的对象)、$router(具备功能函数)
    • 查询字符串
      • 1:去哪里 <router-link :to="{name:'detail',query:{id:1} } ">xxx</router-link>
      • 2:导航(查询字符串path不用改) { name:'detail' , path:'/detail',组件}
      • 3:去了干嘛,获取路由参数(要注意是query还是params和对应id名)
        • this.$route.query.id
    • path方式
      • 1:去哪里 <router-link :to="{name:'detail',params:{name:1} } ">xxx</router-link>
      • 2:导航(path方式需要在路由规则上加上/:xxx)
      • { name:'detail' , path:'/detail/:name',组件}
      • 3:去了干嘛,获取路由参数(要注意是query还是params和对应name名)
        • this.$route.params.name

    编程导航

    • 不能保证用户一定会点击某些按钮
    • 并且当前操作,除了路由跳转以外,还有一些别的附加操作
    • this.$router.go 根据浏览器记录 前进1 后退-1
    • this.$router.push(直接跳转到某个页面显示)
      • push参数: 字符串 /xxx
      • 对象 : {name:'xxx',query:{id:1},params:{name:2} }

    重定向和404

    • 进入后,默认就是/
    • 重定向 { path:'/' ,redirect:'/home' }
    • 重定向 { path:'/' ,redirect:{name:'home'} }
    • 404 : 在路由规则的最后的一个规则
      • 写一个很强大的匹配
      • { path:'*' , component:notFoundVue}

    多视图

    • 以前可以一次放一个坑对应一个路由和显示一个组件
      • 一次行为 = 一个坑 + 一个路由 + 一个组件
      • 一次行为 = 多个坑 + 一个路由 + 多个组件
    • components 多视图 是一个对象 对象内多个key和value
      • key对应视图的name属性
      • value 就是要显示的组件对象
    • 多个视图<router-view></router-view> -> name就是default
    • <router-view name='xxx'></router-view> -> name就是xxx

    嵌套路由

    • 用单页去实现多页应用,复杂的嵌套路由
    • 开发中一般会需要使用
    • 视图包含视图
    • 路由父子级关系路由
    期组件内包含着第一层router-view
    { name:'music' ,path:'/music', component:Music ,
    children:[   子路由的path /就是绝对路径   不/就是相对父级路径
        {name:'music.oumei' ,path:'oumei', component:Oumei },
        {name:'music.guochan' ,path:'guochan', component:Guochan }
    ]
    }  
    

    相关文章

      网友评论

          本文标题:vue-router配置

          本文链接:https://www.haomeiwen.com/subject/hwethftx.html