• 4.怎么定义 vue-router 的动态路由? 怎么获取传过来的值


    在router目录下的index.js文件中,对path属性加上/:id。 

    使用router对象的params.id 例如 :  this.$route.params.id

    详解:https://blog.csdn.net/weixin_41399785/article/details/79381357

    路由的定义,主要有以下几步:

    1. 如果是模块化机制,需要调用 Vue.use(VueRouter)

    2. 定义路由组件,如:

      const Foo = {
         template: '<div>foo</div>'
      };
      • 1
      • 2
      • 3
    3. 定义路由(数组):

      const routes = [
         {
             path: '/foo',
             component: Foo
         }
      ];
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    4. 创建 router 实例

      const router = new VueRouter({
         routes
      });
      • 1
      • 2
      • 3
    5. 创建和挂载根实例

      const app = new Vue({
         routes
      }).mount('#app');
      • 1
      • 2
      • 3

    嵌套路由主要是通过 children,它同样是一个数组:

    {
        path: '/user',
        component: User,
        children: [
            {
                path: 'file',
                component: File
            }
        ]
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    这时访问,/user/file 会映射到 File 组件

    动态路由的创建,主要是使用 path 属性过程中,使用动态路径参数,以冒号开头,如:

    {
        path: /user/:id
        component: User
    }
    • 1
    • 2
    • 3
    • 4

    这会是访问 user 目录下的所有文件,如 /user/a 和 /user/b,都会映射到 User 组件

    当匹配到 /user 下的任意路由时,参数值会被设置到 this.$route.params 下,所以通过这个属性可以获取到动态参数,如:

    const User = {
        template: '<div>User {{ $route.params.id }}</div>'
    }
    • 1
    • 2
    • 3

    这里会根据访问的路径动态的呈现,如访问 /user/aaa 会渲染:

    <div>
        User aaa
    </div>
  • 相关阅读:
    jQuery横向手风琴
    jQuery宽屏游戏焦点图
    手风琴式相册图片展开效果
    鼠标悬停图片分享按钮动画
    jQuery水平滑动菜单
    jQuery图片水平滑动延迟加载动画
    jQuery悬浮焦点图宽屏
    jQuery自定义美化下拉框
    纯CSS3垂直动画菜单
    面向服务与微服务架构
  • 原文地址:https://www.cnblogs.com/dream111/p/13493519.html
Copyright © 2020-2023  润新知