How to solve the problem of data dependency between vue components?

problem description:
the login information returned by the interface in component An is required to perform other operations based on this login information in component B

what I"m doing now is to store the login information in component An in a global variable, and then get the global variable in component B mounted through the getList function.

now there is a problem, that is, after the rendering of component B is completed, the interface in component A has not been successfully requested, so the returned login information cannot be obtained. After the interface request of component A succeeds and assigns the value to the global variable, component B will no longer execute the getList method, so the view still cannot be rendered.

I think of a solution is to add a timer to the getList method in component B to delay execution, which can also achieve the desired results, but I always feel that the practice is not very appropriate. Do you have any good solutions here?

description
1. The project does not use vuex
2. Eventbus has been used for component communication before, but because component B is a common component, several different routes will jump to this component, and the data will not be updated when the route is switched, so the last thing to do is to define the global variable to pass the value

.
Mar.08,2021

in fact, it is good to use vuex in this situation. It can solve your needs perfectly, and it is not complicated to use the module defined in
store

.
import { mapGetters } from 'vuex'
computed: {
  ...mapGetters([
    'name'
  ])
}

<div>{{name}}</div>

this method, which triggers another component after data is available, is done by eventBus.
bus.$on listens in component B, and bus.$emit triggers events in component A.


if component An is a child of component B, it is processed with emit.
if you are a sibling component and jump from component A to component B, why not wait for the login to succeed?
if there is no page jump, consider making a custom event, or use vuex

Menu