vue vue-router 基本使用

官方教程: https://cn.vuejs.org/v2/guide/

vue-route

由于这不是vue必须的,但是在使用前需要先安装vue
并且在使用前必须引入vue.js因为vue-router是依赖vue.js的

安装

npm install vue vue-router --save

路由

  • 什么是路由?

访问不同的路径,就可以返回不同的结果

  • 使用路由 vue-router

由于vue-router是基于vue的所以在使用前必须行引入vue




基本路由

// 实例化vue-router
let vueRouter = new VueRouter({
    routes: [
        {path: "/home", component: home},
        {path: "/list", component: list},
    ],
});

// 关联到vue实例中使用router属性
const vm = new Vue({
    el: '#app',
    router: vueRouter,
});

在模板中使用 这个全局组件即可
这个组件能够根据 VueRouter 实例中的的routes自动显示或隐藏相应的组件

路由模式 mode

  • hash(default)
  • history.pushStatus('','','path');

如果想在页面中使用 a标签 来访问不同的路由可以设置
则可以设置路由模式 mode 的值为 history,使用
这个全局组件

const vueRouter = new VueRouter({
    routes: [
        {path: "/home", component: home},
        {path: "/list", component: list},
    ],
    mode: 'history',
});
  • 在模板中使用 组件
去首页 去列表页

注:使用 组件是必须加上 to
属性,to 的值是 vueRouter 实例中 routes 配置的路由项
点击哪个就会显示路由对应的组件

  • 默认路由
const vueRouter = new VueRouter({
    routes: [
        {path: "", component: home}, // a默认路由
        {path: "/home", component: home},
        {path: "/list", component: list},
        {path: "/*", redirect: '/home'} // b默认路由
        // redirect 是重定向
    ],
    mode: 'history',
});
  1. a默认路由: 没有任何路由时候,显示这个路由对应的组件
  2. b默认路由: 没有匹配到任何路由时,显示这个路由对应的组件
  3. : 因为路由匹配顺序的原因,这a必须第一个 b必须在 最后一个
    在需要匹配 404 时 建议使用这种方式
  • 设置路由连接的样式
    • 设置路由标签(默认a标签)
    • 设置当前路由样式

去首页 列表页




编程式路由




    
    Vue For Vue-Router
    
    
    



路由嵌套




    
    vue vue-router study
    
    
    
    




路由(路径)参数




    
    vue vue-router study
    
    



第一篇文章 第二篇文章 第三篇文章

路由切换动画




    
    vue vue-router 路由切换动画
    
    
    



去首页页 去列表页

你可能感兴趣的:(vue vue-router 基本使用)