美文网首页
(1)关于路由传参的方法,并根据动态参数请求数据

(1)关于路由传参的方法,并根据动态参数请求数据

作者: 自律财富自由 | 来源:发表于2018-08-24 11:32 被阅读0次

需求:根据不同的列表id,向后台请求数据显示页面

编程式导航的两种方法

方法一: 在router.js文件中进行路由的配置---带参数
import Vue from 'vue'
import Router from 'vue-router'
import A from '@/pages/files/A'
import B from '@/pages/files/B'

Vue.use(Router)

export default new Router({
//  '/'代表@/pages/files
  routes: [
    {
      path: '/',
      component: A
    },
    {
      path: '/B/:id', //  这里就是绑定的不同的id
      component: B
    }
  ]
})

组件A页面的click方法中,注意这里是this.$router

this.$router是全局路由对象, 任何页面 都可以 调用 push(),go()等方法

this.$router.push({ path:/mCouponsDetail/${id}})

组件B页面的created方法中获取这个id,而这里是this.$route

this.$route 表示当前正在用于跳转的路由器对象,可以调用其name、path、query、params等属性;
console.log(this.$route.params)
//打印结果
{id: 123}
方法二: 在router.js文件中进行命名路由的配置---使用name指定
export default new Router({
  routes: [
    {
      path: '/',
      component: A
    },
    {
      path: '/B',
      name: 'B',
      component: B
    }
  ]
})
组件A页面的click方法中

this.$router.push({name: 'B', params: {id: id}})

组件B页面的created方法中获取这个id
console.log(this.$route.params)
//打印结果
{id: 123}

使用<router-link>标签的方法

export default new Router({
//  '/'代表@/pages/files
  routes: [
    {
      path: '/',
      component: A
    },
    {
      path: '/B/:id', //  这里就是绑定的不同的id
      component: B
    }
  ]
})
注意to前面要使用冒号!

<router-link :to="/mCouponsDetail/${item.cid}"></router-link>

获取到参数之后,请求数据

    created () {
        this.fetchData()
    },
    methods: {
        fetchData () {
            let id = this.$route.params.id
            let url = `/api/coupon/detail?id=${id}`
            axios.get(url).then((res) => {
                this.showLoading = false
                console.log('res = ', res)
            })
        }
    },
    watch: {
        // 如果路由有变化,会再次执行该方法
        '$route': 'fetchData'
    }
watch方法不可缺少,因为点击不同的代金券,id发生了变化,请求的数据也不一样

相关文章

网友评论

      本文标题:(1)关于路由传参的方法,并根据动态参数请求数据

      本文链接:https://www.haomeiwen.com/subject/ntkbiftx.html