动态路由传值

2021-04-05  本文已影响0人  波仔_4867

动态路由: 能够传递参数的路由即为动态路由

在路由不变,参数发生变化时,不会再触发created,因为组件会被复用。

如果要监测参数的变化,应该 使用watch来监测$route

一、声明式导航传值

第一种


例如:路由地址是index 值是id
<router-link :to="`/index/${id}`">标签</router-link>
 路由配置:
            {
                path: '/index/:id',
                component: index
            }
 接收参数: 在组件中 this.$route.params.id

第二种路由地址是index 值是id 这种方式不需要在路由表中配置

<router-link :to="{name: 'index ', params: {id}}">图书列表</router-link>
用this.$route.params接收

<router-link :to="{path: 'index ', query: {id}}">图书列表</router-link>
用this.$route.query接收 等价于:  '/index ?id'

二、编程式导航传值

1.路由地址是index 值是id 这种方式不需要在路由表中配置

this.$router.replace({name: 'index ', params: {id}})
用this.$route.params接收

this.$router.replace({path: 'index ', query: {id}})
用this.$route.query接收 等价于:  '/index ?id'

query和params的区别是

query方法传参时参数是显示在url地址上的

  params方法传参时参数是不显示在url地址上的,安全性高

2.路由地址是index 值是id

需要在路由表中配置

this.$router.replace({path:`/index${id}`})
 路由配置:
            {
                path: '/index/:id',
                component: index
            }
 接收参数: 在组件中 this.$route.params.id

通过props来获取动态路由的参数

第一步:传参方式

<router-link :to="/index/3">图书列表</router-link>

第二步:在路由配置中添加props: true

const routes = [{
    {
        path: '/Index',
        component: Index,
        props: true 
    }]

第三步: 在组件内部通过props接收参数值

data(){
    return{
       props:['id']
    }
}
此时id就可以当做响应式数据使用了
上一篇 下一篇

猜你喜欢

热点阅读