8 ways for Vue routing components to transmit parameters

When developing a single page application, we sometimes need to obtain data from the server based on the parameters after entering a route, so we first need to obtain the parameters passed by the route to complete the server request. Therefore, we need to understand several methods of routing parameters, the following methods are the same as vue-router@4 .

Programming routing parameters

In addition to using < router link > to create a tag to define navigation links, we can also use router's instance method to write code.

1. Pass through params

Routing configuration

The path parameter {is represented by a colon:.

const routes = [
  //The dynamic segment starts with a colon
  { path: 'details/:id', name: "details", component: Details },
]

router. The parameter of the push () method can be a string path or an object describing the address.

const Home = {
  template: '<div @click="toDetails">To Details</div>',
  metheds: {
    toDetails() {
      //String path
      this.$router.push('/details/001')
      //Object with path
      this.$router.push({path: '/details/001'})
      //Name the route. When configuring the route, you need the {name} field
      this.$router.push({ name: 'details', params: { id: '001' } })
    }
  }
}

Note that params , will be ignored if , path is provided:

//'params' cannot be used with' path '
router.push({ path: '/details', params: { id: '001' } }) // -> /details

Component get data

When a route is matched, its params value will be marked with this in each component$ route. Params are exposed.

const Details = {
  template: '<div>Details {{ $route.params.id }} </div>',
  created() {
    //Listen for routing changes
    this.$watch(
      () => this.$route.params,
      (toParams, previousParams) => {
        //Respond to routing changes
      }
    )
  },
}

2. Pass through query

In this case, the parameters passed by query will be displayed after the url, such as: / details/001?kind=car.

Routing configuration

When using query, the following three methods are feasible:

this.$router.push('/details/001?kind=car')
this.$router.push({ path: '/details/001', query: { kind: "car" }})
this.$router.push({ name: 'details', params: { id: '001' }, query: { kind: 'car' }})

Component get data

Component through $route Query get:

const Details = {
  template: '<div>Details {{ $route.query.kind }} </div>',
  created() {
    //Listen for routing changes
    this.$watch(
      () => this.$route.query,
      (toParams, previousParams) => {
        //Respond to routing changes
      }
    )
  },
}

To respond to parameter changes in the same component, you can simply watch any attribute on the $route} object. In this scenario, it is $route query .

3. Pass through {hash}

In this way, the url path has a # hash, such as: / details/001#car.

Routing configuration

When using {hash}, the following three methods are feasible (the same as} query):

this.$router.push('/details/001#car')
this.$router.push({ path: '/details/001', hash: '#car'})
this.$router.push({ name: 'details', params: { id: '001' }, hash: 'car'})

Component get data

Component through $route hash. Slice (1) get:

const Details = {
  template: '<div>Details {{ $route.hash.slice(1) }} </div>',
}

Pass through props

Using $route in a component is tightly coupled with routing, which limits the flexibility of the component because it can only be used for specific URL s. Although this is not necessarily a bad thing, Front end training However, we can disable this behavior through {props} configuration.

Parameters are transferred by using {props} in a decoupled manner, mainly in routing configuration.

1. Boolean mode

When , props , is set to , true , route Params will be set as props of the component.

For example, the following code obtains the dynamic field id through $route +

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const routes = [{ path: '/user/:id', component: User }]

Replace the above code with the form of {props}, as follows:

const User = {
  props: ['id'], //Get the {id through} props} in the component
  template: '<div>User {{ id }}</div>'
}
//In the routing configuration, add the {props} field and set the value} to} true
const routes = [{ path: '/user/:id', component: User, props: true }]

Note: for routes with named views, you must define {props} configuration for each named view:

const routes = [
  {
    path: '/user/:id',
    components: { default: User, sidebar: Sidebar },
    //Provide # props for # User #
    props: { default: true, sidebar: false }
  }
]

2. Object mode

When {props} is an object, it sets as is as component props. It is useful when props is static.

Routing configuration

const routes = [
  {
    path: '/hello',
    component: Hello,
    props: { name: 'World' }
  }
]

Get data from component

const Hello = {
  props: {
    name: {
      type: String,
      default: 'Vue'
    }
  },
  template: '<div> Hello {{ name }}</div>'
}

The < hello / > component displays Hello Vue by default, but the route is configured with a "props" object. When the route jumps to / Hello , the passed "name" will be displayed, and the page will be displayed as Hello World.

3. Function mode

You can create a function that returns props. This allows you to convert parameters to other types, combine static values with route based values, and so on.

Routing configuration

When the function mode is used, the parameters accepted by the function that returns props are route records and route.

//Create a function that returns {props}
const dynamicPropsFn = (route) => {
  return { name: route.query.say + "!" }
}
const routes = [
  {
    path: '/hello',
    component: Hello,
    props: dynamicPropsFn
  }
]

Component get data

When the URL is / Hello? When say = world, {name: 'World!'} will be passed to the {Hello} component as props.

const Hello = {
  props: {
    name: {
      type: String,
      default: 'Vue'
    }
  },
  template: '<div> Hello {{ name }}</div>'
}

The page renders:

Note: please keep the {props} function stateless as much as possible, because it will only work when the route changes. If you need states to define props, use wrapper components so vue can respond to state changes.

Other ways

1. Delivery via Vuex

    1. store Storage status;
    2. A Component changes store Status in;
    3. B Component from store Get from.

2. Through front-end local storage, etc

    1. Local Storage;
    2. Session Storage;
    3. IndexedDB;
    4. Web SQL;
    5. Cookies. 

 

Keywords: Javascript Front-end Vue.js

Added by tat on Thu, 16 Dec 2021 06:55:16 +0200