A collection of vueRouter routing knowledge points (two)

  • The number of parameters is spliced ​​behind the url
// 路由定义
{
    
    
  path: '/describe/:id',
  name: 'Describe',
  component: Describe
}
// 页面传参
this.$router.push({
    
    
  path: `/describe/${
      
      id}`,
})
// 页面获取
this.$route.params.id
  • Programmatic routing navigation params parameter passing parameters will not be spliced ​​behind the routing, page refresh parameters will be lost
// 路由定义
{
    
    
  path: '/describe',
  name: 'Describe',
  omponent: Describe
}
// 页面传参
this.$router.push({
    
    
  name: 'Describe',
  params: {
    
    
    id: id
  }
})
// 页面获取
this.$route.params.id
  • Programmatic routing navigation query parameter number splicing behind the url
// 路由定义
{
    
    
  path: '/describe',
  name: 'Describe',
  component: Describe
}
// 页面传参
this.$router.push({
    
    
  path: '/describe',
    query: {
    
    
      id: id
  `}
)
// 页面获取
this.$route.query.id
  • Decoupling of routing parameters
    Generally, most of the routing parameters used in components are operated in this way.
	export default {
    
    
    methods: {
    
    
        getParamsId() {
    
    
            return this.$route.params.id
        }
    }
}

Using $route in a component will make it highly coupled with its corresponding route, so that the component can only be used on certain URLs, limiting its flexibility.
The correct approach is to decouple through props

const router = new VueRouter({
    
    
    routes: [{
    
    
        path: '/user/:id',
        component: User,
        props: true
    }]
})

After the props attribute of the route is set to true, the params parameter can be received in the component through props

export default {
    
    
    props: ['id'],
    methods: {
    
    
        getParamsId() {
    
    
            return this.id
        }
    }
}

In addition, you can also return props through function mode

const router = new VueRouter({
    
    
    routes: [{
    
    
        path: '/user/:id',
        component: User,
        props: (route) => ({
    
    
            id: route.query.id
        })
    }]
})

Guess you like

Origin blog.csdn.net/qq_38686150/article/details/108664103