zoukankan      html  css  js  c++  java
  • vue小项目总结与笔记【九】——vue中的动态路由

    前面说到了路由配置 vue小项目总结与笔记【二】——vue的单文件组件模板和路由,但其路由导航功能是不能传递参数的,是静态路由。

    静态路由:

    routes: [{
          path: '/',
          name: 'Home',
          component: Home
        }]

    而能传递参数的路由模式,由于可以传递参数,所以其对应的路由数量是不确定的,故称之为 动态路由。那么动态路由如何传递参数?

    在参数名前面加上 : ,然后将参数写在路由的 path 内.如下:

    routes: [{
          path: '/',
          name: 'Home',
          component: Home
        }, {
          path: '/city',
          name: 'City',
          component: City
        }, {
           // 动态路由参数  :id
          path: '/detail/:id',
          name: 'Detail',
          component: Detail
        }]

    这样定义之后,vue-router就会匹配到所有的

    /detail/1, /detail/2, /datail/3......

    <router-link> 我们加入一个 params 属性来指定具体的参数值

            <li>
              <router-link :to ="{params :{id:1}}" >
                <div>首页</div>
              </router-link>
            </li>    

    这时候对应的网址是http://localhost:8080/detail/1。

    如何把参数读取出来?

    路由参数是被设置到 this.$route.params 中的,想取到这个值,用 this.$route.params.id 就可以了。

    例如我想根据点击的景点名,进入对应的景点详情中,

        getDetailInfo () {
                // 相当于 /api/detail.json?id=this.$route.params.id'
                axios.get('/api/detail.json', {
                    params: {
                        id: this.$route.params.id
                    }
                }).then(this.handleGetDataSucc)
        }    

    利用这个取到的id值,去筛选ajax获取到的data数据,就可以实现数据对应了。即:点击第一个,跳转到链接/detail/1,数据也是第一条……

  • 相关阅读:
    Sum Root to Leaf Numbers 解答
    459. Repeated Substring Pattern
    71. Simplify Path
    89. Gray Code
    73. Set Matrix Zeroes
    297. Serialize and Deserialize Binary Tree
    449. Serialize and Deserialize BST
    451. Sort Characters By Frequency
    165. Compare Version Numbers
    447. Number of Boomerangs
  • 原文地址:https://www.cnblogs.com/Ashe94/p/10571459.html
Copyright © 2011-2022 走看看