zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    hdu1074Doing Homework
    1088滑雪
    hdu1078FatMouse and Cheese
    hdu1058Humble Numbers
    hdu1114 Piggy-Bank
    hdu1069Monkey and Banana
    未解决的问题_c#中,最小化触发事件
    WPF Button 样式资源设置&后台生成button样式
    .NET 调用外部exe程序,出现已停止工作
    json类序列化与反序列化参考
  • 原文地址:https://www.cnblogs.com/dream111/p/13493519.html
Copyright © 2011-2022 走看看