SoFunction
Updated on 2025-04-04

Detailed explanation of the method of a component in Vue calling other components (non-parent-child components)

Preface

In Vue, a component calls a method of other components (non-parent-child components)

Scene——Page B (component) wants to call the method in page A (component); but the two pages (component) have no relationship (refresh A's data).

Method 1: Quotation

1. The current component introduces the component to which the method is to be called

Here my current component is to be calledOrderDetailThis component'scheck()method

import Detail from "./";

The method is defined inOrderDetailin the methods attribute

2. The current component directly calls the method through the component methods attribute

// You can also call created, data, etc.();

Method 2: vuex

useVueX defines an attribute, and thenPage A Define a computed property(computed) Return the vuex attribute to it, listen to this computed attribute, and call the method you want to execute if there is any change.

1、src/store/

// Vuex Globalstate: { 
	tableStatus:false  
	 	}
 mutations:{  
	changeStatus(state,status) {  // Repeat assignment       = status;
    },
}

2. Used Components - Page A (Component)

 // Page A (component)computed: {  
  status() {  // Calculate properties    return this.$; // Properties defined in Vuex  }
},
watch:{
  status() {
    ();  // Methods that need to be called  }
},

3. Use trigger page-B page (component)

Then define a click event (for example) on page B and reassign the attributes in Vuex

// Page B (component)closePage() {
    let status = this.$;   // Reassign value    this.$("changeStatus", !status);
},

Method 3: Use eventbus eventBus to define global events

1、src/

  = new Vue();

2. Trigger page-B component/Publish event

.$emit('setFeaturesData', data)  // With parameters.$emit('setFeaturesData')  // No parameters

3. Receive page-A component/subscribe event

    .$on('setFeaturesData', (data)=>{ // With parameters       = [data]
      ()
    })

  mounted() {
    ()
    .$on('setFeaturesData', ()=>{ // No parameters      ()
    })
  },

4. Remove the event

.$off('setFeaturesData')

Summarize

This is the end of this article about a component calling other components (non-parent and child components) in Vue. For more related content on Vue component calling other components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!