01. Route parameters are transmitted

(1) Dynamic route matching

  • You can configure dynamic routing to match a pattern to all routes and map them to the same component

  • Dynamic route matching: Dynamic path parameters are used in routing paths for matching, which essentially uses URLS to pass parameters

/ / routing
const router = new VueRouter({
    routes: [
        // Dynamic path parameters start with a colon
        { path: '/user/:id'.component: User }
    ]
})

// Pass parameters
// 1
<router-link :to="/user/1"> Jump to a matching route </router-link>// 2. Program
this.$router.push({
    path: '/child/${id}',})Copy the code

(2) URL parameter transmission mode

(a) AdoptionparamsExplicit arguments

  • Routing configuration: Needs to be in the routing componentpathAfter the configuration parameter, pass the colon:Is marked in the form of
  • Pass parameters: Parameters are set directly after the URL path of the route to jump to
  • Receiving parameters:This $route. Params. Parameter nameReceive parameters
/ / routing
const routes = [{
    path: '/child/:id'.name: 'Child'.component: () = > import('@/components/Child')}]// Pass parameters
this.$router.push({
    path: '/child/foo',})// Accept arguments
this.$route.params.id === foo
Copy the code

Note: /child/foo and /child/bar reuse the same component instance child

Therefore, the component’s lifecycle hook function is not called repeatedly

// You can also configure multiple parameters
const routes = [{
    path: '/user/:name/hobby/:id'.component: UserComponent
}]

Username = [:name], userHobby = [:id]
// The other fields must be exactly the same, otherwise they cannot be matched
this.$router.push({
    path: '/user/userName/hobby/userHobby'
})
// Receive parameters
this.$route.params.name === userName
this.$route.params.id === userHobby
Copy the code

(b) AdoptionparamsImplicit reference

  • Route configuration: Routes need to be configurednameProperty to match
  • Pass parameters: When passing parameters, set the parameters toparamsIn the object
  • Receive parameters: YesThis $route. Params. Parameter nameReceive parameters
/ / routing
const routes = [{
    path: '/child'.name: 'Child'.component: () = > import('@/components/Child')}]// Pass parameters
this.$router.push({
    name: 'Child'.params: {
        id: 1}})// Receive parameters
this.$route.params.id === 1
Copy the code

(c) AdoptionqueryPassing parameters

  • Route configuration: The route passesnameProperties, orpathAttribute to match the route
  • Pass parameters: When passing parameters, set the parameters toqueryIn the object
  • Receiving parameters: Last passthis.$route.query.idReceive parameters
/ / routing
const routes = [{
    path: '/child'.name: 'Child'.component: () = > import('@/components/Child')}]// Pass parameters (match routes by name or path)
this.$router.push({
    path: '/child'.query: {
        id: 1}})// Receive parameters
this.$route.query.id === 1
Copy the code

(d)paramsqueryThe difference between

  • When params explicitly passes a parameter

    • It must be in the route configurationpathAdd the parameter name after
    • And the parameters become part of the route:/child/123
    • Parameters are not lost when the page is refreshed
  • When params implicitly passes a parameter

    • Need to usenameAttribute matching parameter
    • Parameters are not displayed on the path and will be cleared when the page refreshes

  • When passing a parameter with query

    • You can usepathProperties andnameProperty to match routes
    • queryThe parameters are displayed in the URL bar as normal:/child? id=123
    • Page refresh does not clear parameters

  • Set params and Query parameters at the same time

    • If you usenameBoth object parameters can be passed
    • If you usepathTo match, only passqueryparameter
    • If you usenameandpathTo match, will benameGive priority to
      • That is, both object parameters can be passed

(3) Props pass parameters

  • throughparamsandqueryParameter transmission, its essence is to use the URL parameter transmission, that is, by changing the URL
    • This results in a high degree of coupling between parameters and components
  • In this case, you can useroutesthepropsAttributes decouple components and parameters to improve component reuse without changing urls

(a) Boolean type

  • Route configuration: willpropsSet to true, thenroute.paramsThrough properties in the component definitionpropsTo receive routing parameters and then use routing parameters through interpolation expressions
  • Pass parameters: Parameters are configured after the URL path
  • Receive parameters: pass within the componentpropsProperty to receive parameters
// Simple parameter passing
// Routing: configure the dynamic path parameters and enable props
const routes = [{
    path: '/user/:id'.component: User,
    props: true
}] 
// Pass parameters
this.$router.push('/user/123')
// Accept parameters: the components use props to accept parameters, which can be used as data in data
const User = {
    props: ['id'].template: '<div>{{ id }}</div>'
}
Copy the code
// Pass complex parameters
// Routing: just enable props
const routes = [{
    path: '/user'.name: 'User'.component: User,
    props: true
}]
// Pass parameters
this.$router.push({
    name: 'User'.params: {
        user: {
            name: 'black'.age: 18}}})// Receive parameters
// The props inside the component receive parameters, which can be used as data in data
const User = {
    props: ['user'].template: '
      
{{user.name}}, {{user.age}}
'
} Copy the code

(b) Object type

  • Route configuration: willpropsSet to object format to store parameters, in which case the route parameter is a colon:The following parameters are invalid
    • Note: at this timepropsObject data is static content, that is, fixed data
  • Pass parameters: At this point, you can still passparamsorqueryPass parameters in the form of
    • The way it accepts parameters is as follows:This.$route. Object parameter
  • Receive parameters: in the component definitionpropsAttribute receiving parameter
/ / routing
const routes = [{
    path: "/user/:id".// The id here will be invalid
    component: User,
    // Configure static parameters by object type
    props: {
        id: 123}}]// Pass parameters
this.$router.push({
    ...
})
// Receive static parameters
this.id === 123
Copy the code

(c) Function types

  • Route configuration: Set to function

    • This function takes one argument, the current route objectroute
    • This function returns an object
    • In the function, static values and route-dependent values can be processed
    • Can bepathProperties of the colon:The following parameters are passed along with those defined by the componentpropsProperties of the
      • In this case, the dynamic path parameter needs to be usedThe route. The params. ParametersTo receive the
  • Pass parameters: The parameters are set in the Params object, or in the Query parameter

  • Receive parameters: Receive parameters within the component via the props property

    / / routing
    const routes = [
        {
            path: "/user".component: User,
            // Function type that accepts route arguments
            props: route= > ({
                userName: route.query.name,
                userAge: route.query.age
            })
        }
    ]
    // Pass parameters
    this.$router.push({
        path: '/user'.query: {
            name: 'black', the age;18}})// Receive parameters
    const User = {
        props: ['userName'.'userAge'].template: 
            
    {{userName}}, {{userAge}}
    '
    } Copy the code
    • Function types can also get dynamic path parameters, using Params

      Note:

      If the path attribute is used for route matching, only query object parameters can be configured, and params object parameters are invalid

      • But if thepathIf the dynamic path parameter is configured, it will be configured in theparamsIn the object
    / / routing
    const routes = [
        {
            path: "/user/:id".component: User,
            props: route= > ({
                queryId: route.params.id // Get dynamic path parameters})}]// Pass parameters
    this.$router.push({
        path: 'user/123' // The dynamic path parameter is received by the params object
    })
    // Receive parameters
    const User = {
        props: ['queryId'].template: '<div>{{ queryId }}</div>'
    }
    Copy the code

02. $route$routerThe difference between

  • $route is an object to get routing information

    / / such as:
    export default {
        created(){
            let id = this.$route.params; // Get params object parameters, empty if no route parameters
            let query = this.$route.query; // Get query parameters, null if none
            let name = this.$route.name; // Get the name of the current route
            
            let hash = this.$route.hash; // Get the hash value of the current route, including #, or an empty string if no
            let path = this.$route.path; // Get the path of the current routing object - absolute path
            let fullPath = this.$route.fullPath; // Gets the full URL of the current route, including the query parameters and the full path to the hash
            
            let matched = this.$route.matched; // Obtain all information and records of the route declaration under the current route
            let redirectedForm = this.$route.refirectedForm; // Get the source route of the current route redirection (if any)}}Copy the code
  • $router is a route instance object for route hops

    / / such as:
    export default {
        methods: {
            toRoute(){
                this.$router.push({
                    path: '... '.// Jump path
                    params: {}, / / params parameters
                    query: {} / / query parameters
                });
                this.$router.replace({}); // Replace the current route
                this.$router.go(1); // Forward and backward}}}Copy the code

I front-end side dish chicken, if there is wrong, please forgive