Detailed explanation of 8 ways to pass parameters in Vue routing components

Detailed explanation of 8 ways to pass parameters in Vue routing components

When we develop a single-page application, sometimes we need to enter a certain route and get data from the server based on parameters. Then we must first get the parameters passed by the route to complete the server request. Therefore, we need to understand several ways of passing parameters by the route. The following methods are the same as vue-router@4 .

Programmatic routing parameters

In addition to using <router-link> to create a tag to define navigation links, we can also use the instance method of router to implement it by writing code.

1. Pass through params

Routing Configuration

Path parameters are represented by a colon :

const routes = [
 // Dynamic sections start with a colon { path: 'details/:id', name: "details", component: Details },
]

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

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

Note that if path is provided, params are ignored:

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

Components get data

When a route is matched, the value of its params will be exposed in every component as this.$route.params .

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

2. Pass through query

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

Routing Configuration

When using query , the following three methods are all possible:

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' }})

Components get data

Components are obtained through $route.query :

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

To respond to parameter changes within the same component, you can simply watch any property on the $route object, in this case, $route.query .

3. Passing via hash

In this way, the url path contains hash , for example: /details/001#car .

Routing Configuration

When using hash , the following three methods are all feasible (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'})

Components get data

The component is obtained through $route.hash.slice(1) :

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

Passing via props

Using $route in a component is tightly coupled to the router, which limits the flexibility of the component as it can only be used for a specific URL. While this isn't necessarily a bad thing, we can override this behavior via props configuration.

Use props to pass parameters in a decoupled manner, mainly in route configuration.

1. Boolean mode

When props is set to true , route.params will be set as the component's props.

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 props as follows:

const User = {
 props: ['id'], // Get 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 will be set as component props as is. Useful when props are static.

Routing Configuration

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

Get data in 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 display Hello World.

3. Functional 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 more.

Routing Configuration

When using the function mode, the function that returns props receives route record as a parameter.

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

Components get data

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

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

At this point the page will render:

Note: Keep the props function as stateless as possible, as it will only be used when the route changes. If you need state to define props, use a wrapper component so vue can react to state changes.

Other ways

1. Pass through Vuex

1. store storage status;
2. Component A changes the state in the store;
3. Component B is obtained from the store.

2. Through front-end local storage and other methods

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

This concludes this article about 8 ways to pass parameters in Vue routing components. For more information about passing parameters in Vue routing components, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution for Vue asynchronous component to handle routing component loading status
  • Summary of several methods for loading Vue routing components on demand
  • Detailed explanation of how to use Vue.js routing component vue-router
  • Add axios component based on vue to solve the problem of null post parameters
  • How to pass parameters between vue-router2.0 components and obtain dynamic parameters
  • Vue.js parameter transfer example between parent and child components

<<:  Detailed explanation of the working principle and usage of the Docker image submission command commit

>>:  MySQL 5.5 installation and configuration graphic tutorial

Recommend

Ubuntu 20.04 sets a static IP address (including different versions)

Because Ubuntu 20.04 manages the network through ...

Summary of Vue3 combined with TypeScript project development practice

Table of contents Overview 1. Compositon API 1. W...

Example of using CSS3 to customize the style of input multiple-select box

Principle: First hide the input element, then use...

js to achieve the complete steps of Chinese to Pinyin conversion

I used js to create a package for converting Chin...

Detailed explanation of CSS background and border tag examples

1. CSS background tag 1. Set the background color...

Four practical tips for JavaScript string operations

Table of contents Preface 1. Split a string 2. JS...

A useful mobile scrolling plugin BetterScroll

Table of contents Make scrolling smoother BetterS...

Example code for text origami effect using CSS3

Preface This article mainly shares with you an ex...

Common pitfalls of using React Hooks

React Hooks is a new feature introduced in React ...

Vue sample code for online preview of office files

I'm working on electronic archives recently, ...

How to understand Vue's simple state management store mode

Table of contents Overview 1. Define store.js 2. ...

Vue directives v-html and v-text

Table of contents 1. v-text text rendering instru...

mysql5.6.zip format compressed version installation graphic tutorial

Preface: MySQL is a relational database managemen...