• 孙卫琴的《精通Vue.js》读书笔记-命名路由


    本文参考孙卫琴,杜聚宾所创作的 <<精通Vue.js: Web前端开发技术详解>>一书
    在这里插入图片描述
    路由可以通过name属性来设置名字,这样便于在其他场合引用路由。在src/router/index.js文件中,为Items组件以及Item组件的路由分别设定名字“items”和“item”:

        {
          path: '/items',
          name: 'items',
          alias: '/products',
          component: Items,
          children:[
            {
              path: 'item/:id',
              name: 'item',
              component: Item  
            }
          ]
        },
        {
           path: '/list',
           redirect: {  //重定向
             name: 'items'
           }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    修改src/App.vue文件,在设置Items组件的导航链接时通过名字来指定路由:

    商品清单
    
    • 1

    简写为:

    商品清单
    
    • 1

    由于上述组件的to属性是一个对象表达式,所以需要通过v-bind指令来为to属性赋值。如果不使用v-bind指令,直接按照以下方式为to属性赋值,会把“{ name: ‘items’}”当作一个普通的字符串处理:

    商品清单
    
    • 1

    修改src/components/Items.vue文件,在设置Item组件的导航链接时通过名字来指定路由:

        
    • {{item.title}}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    以上组件的to属性的取值为{name: ‘item’, params: {id: item.id}},params属性用来为路径中的id路径参数赋值。
    做了上述修改后,再次运行helloworld项目,会发现通过路由的名字,也能在网页上正确地导航到Items组件和Item组件。

    1.重定向

    在index.js中增加一个路由,用于把“/list”重定向到名字为“items”的路由:

        {
           path: '/list',
           redirect: {
             name: 'items'
           }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    通过浏览器访问:
    http: //localhost:8080/#/list

    会看到浏览器的地址栏中的URL会重定向到以下链接:
    http: //localhost:8080/#/items

    2.使用别名

    在index.js中为Items组件的路由设定别名“/products”:

        {
          path: '/items',
          name: 'items',
          alias: '/products',
          component: Items,
          ……
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    通过浏览器访问:
    http: //localhost:8080/#/products

    会看到浏览器显示的网页与以下链接相同:
    http: //localhost:8080/#/items

    不过,在浏览器的地址栏,仍然保持URL为“http: //localhost:8080/#/products”,而不会像重定向那样,把地址栏的URL改为重定向后的链接。

  • 相关阅读:
    JVM 面试题
    二十四、 Java 抽象类
    SpringCloud Alibaba微服务第7章之Nacos
    XA分布式事务处理
    JAVA基础语法
    全国2021年夜间灯光数据,有图有数据
    【笔记篇】10仓管系统库内管理——之《实战供应链》
    Leetcode 1582. 二进制矩阵中的特殊位置
    力扣(LeetCode)84. 柱状图中最大的矩形 (C++)
    day36-IO流03
  • 原文地址:https://blog.csdn.net/csdnuserlala/article/details/126604569