What are the ways to communicate with Vue components?

Reference: Vue communication, multiple ways of passing values ​​(detailed)
The use of eventBus in Vue component communication

Vue communication and value transfer between components

1. Pass values ​​through routing with parameters

  1. Two components A and B, A component passes orderId to B component through query:this.$router.push({ path: '/conponentsB', query: { orderId: 123 } }) // 跳转到B
  2. Get the parameters passed by component A in component B:this.$route.query.orderId

2. Pass by setting the Session Storage cache

  1. Two components A and B, set the cache orderData in the A component:const orderData = { 'orderId': 123, 'price': 88 }; sessionStorage.setItem('缓存名称', JSON.stringify(orderData))
  2. The B component can get the cache set in A:const dataB = JSON.parse(sessionStorage.getItem('缓存名称'))

3. Passing values ​​between parent and child components

(1) props from parent to child
  1. Define the parent component
  2. Define the child component, the child component obtains the value passed by the parent component through the props method. The data type that can be received can be defined in props, and an error will be reported if it does not match

note: The parent and child components pass values, and the data are all asynchronous requests. It is possible that an error will be reported during data rendering.
Reason : In the asynchronous request, the data has not been obtained but the node has been rendered at this time
**Solution:** You can add it to the node where the parent component needs to pass the data v-if = false. After the asynchronous request to obtain the data,v-if = true

(2) The child component passes the value to the parent component through the emit event

4. Different components pass values ​​through eventBus

Implementation approach : In the brother components that want to communicate with each other, introduce a new vue instance, and then implement communication and parameter transfer by calling the event trigger and monitoring of this instance respectively.
Example: The click component and the show component are brother components. After the click event is triggered in the click component, which dom element will be clicked by the show component console

  1. First, add a click event to the click component and define the method: doClick()
  2. Create a new js file, create eventBus, import it in the click and show components
  3. In doClick(), trigger an event
  4. In the created() hook in the show component, call bus to listen for this event and receive parameters

5. Use vuex for value transfer

Vuex mainly does data interaction and maintains public state or data.

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108354622