Can methods with attributes from one component be invoked in another in Vue2Js?

In my project, I have 3 main Components that are crucial for the functionality: Component 1 serves as the Top Menu, Component 2 is like a library containing various functions, and Component 3 houses the main code.

My goal is to utilize a method from Component 2 within Component 1 while also incorporating attributes from Component 3. Additionally, I aim to integrate Component 1 into Component 3.

// Component 1 Top Menu
Vue.component('component1', {
    props: {
        titleTest: {
            type: String,
            required: true
        },
        textTest: {
            type: String,
            required: true
        }
    },
    template: `
    <div>
        <div :title="titleTest">{{ titleTest }}</div>
        <div :data-test="textTest">{{ textTest }}</div>
        <button id='test' type="submit" @click="bar">TestButton</button>
    </div>
    `,
    created() {
        console.log('Created1');
        this.$root.$refs.component1 = this;
    },
    methods: {
        //alertText should be passed from Component 3
        bar: function(alertText) {
            console.log(alertText);
            this.$root.$refs.component2.foo(alertText);
        }
    }
});

// Component 2 Lib
Vue.component('component2', {
    created() {
        this.$root.$refs.component2 = this;
    },
    methods: {
        foo: function(alertText) {
            alert('this is component2.foo' + alertText);
        }
    }
});

// Component 3 Main Code
Vue.component('component3', {
    template: `
    <div>
        <div>Some text</div>
        <ul>
            <li>List Item1</li>
            <li>List Item2</li>
        </ul>
        <div>
            <component1 ref="component1" :title-test="test1" :text-test="test2"></component1>
        </div>
    </div>
    `,
    data: function() {
        return {
            test1: 'testText1',
            test2: 'testText2',
            alertText: 'alertText'
        };
    },
    created: function() {
    }
});

new Vue({
    el: '#plotlyExample',
});

I am unsure if this setup is feasible, as I attempted using "emits" without success.

Answer №1

By utilizing the

Vue.component('component2', {...})
method, you are simply informing Vue of a named component without actually creating an instance of it. In order to access the methods of component2, the component must be rendered or mounted. Perhaps consider alternative approaches such as utilizing mixins, provide/reject functionality, or incorporating vuex for improved management.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Most effective method for exporting data to a JSON file

I possess an array of weather data for various "stations," with most being situated at airports. This data has been gathered from web APIs and is currently presented as unordered arrays. As an example: Station: Chicago (O'Hare Airport) Temperature: ...

Creating interactive table headers and values with dynamic functionality in Vuetify's data table

Is there a way to achieve a "dynamic table header column" using an array object in conjunction with a vuetify data table? Can this task be accomplished similarly to the example below: ---------------------------------------------- | Employee Id | T ...

Basic JavaScript framework centered around the Document Object Model (DOM) with a module structure similar to jQuery. Currently facing challenges with

In order to create a simple framework with jQuery style, I have written the following code: (function(window) { window.smp=function smpSelector(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; if (!s ...

Error message: SDL2 (emscripten) is encountering an unidentified data structure called "SDL_RendererFlip"

I have attempted to compile an SDL2 tutorial using emscripten found at this link: Text input tutorial However, I encountered the following error: error: unknown type name 'SDL_RendererFlip'; did you mean 'SDL_RendererFlags'? error: us ...

Comparison of Web Development Techniques: localStorage versus Cached HTTP

Imagine a scenario where there is a web server responding to a GET request by sending a .json file. The response instructs the browser to cache it for a period of 5 years. Furthermore, picture a webpage that initiates this GET request for the JSON data du ...

Initiating and canceling a transaction involving a Mongoose database connection

I'm struggling to figure out how to initiate and rollback a transaction. I assumed session.abortTransaction() would revert all the changes made in the transaction, specifically Profile.updateOne. However, when I executed the code below, the username o ...

What is the best way to handle an AJAX JSON response in AngularJS?

Need help with extracting properties from a JSON object returned by a REST service in AngularJS? Want to parse the firstName, lastName, and other attributes from the JSON response? Check out the code snippets below for guidance. Here is an example of an A ...

Drop your friend a line, I'm curious about the Javascript API

As a developer hailing from the Republic of Korea, I am currently in the process of creating websites that are based on Facebook and Twitter. I am interested in utilizing a JavaScript API that allows me to send messages to friends. Initially, I considered ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Loading custom fonts using @font-face will only happen as the last step

Within my project.less file, I have declared several fonts to load: @font-face { font-family: 'Myriad Set Pro'; src: url(/assets/fonts/Myriad-Apple-Text/myriad-set-pro_medium.woff) format('woff'); //font-style: normal; ...

Is there a way to set up my node package to automatically load sources without having to specifically mention the src directory?

My Node package is structured as follows: ./my-package ./src ./index.js ./a.js ./b.js README.md package.json The package.json file specifies "main": "./src/index.js" and the module loads correctly. However, to import a specific JavaScri ...

Ways to dynamically access the name of ng-model?

Is there a way to dynamically access the ng-model name assigned to each div within a for loop in a function triggered by an ng-click event? I have four divs on my page and I only want to display one at a time while hiding the others. My current approach i ...

Unfortunately, the Ajax functionality is not performing as expected

What am I missing? 2.php: <button id = "Text_Example">Display</button> <script src="jquery-3.1.1.min.js"></script> <script src="js_code.js"></script> js_code.js: $("#testtext").bind("click", displayNewData); functio ...

Alter Text Using Typewriter

Recently, I have been experimenting with code on my glitch website, trying to create typewriter text. Thanks to help from a user on StackOverflow, I was able to achieve this effect successfully. However, I am now facing a new challenge. My goal is to make ...

Issue with Cordova ListPicker plugin while using the Ripple emulator

Currently, I am utilizing Cordova within Visual Studio and have successfully integrated the ListView plugin from this source. The addition of the plugin was done through the config.xml editor screen. While trying to execute window.plugins.listpicker.showP ...

What steps can I take to address the Uncaught TypeError error indicating that pendingLegacyContextWarning.forEach is not a function?

Oh no! I encountered a React error stating "Uncaught TypeError: pendingLegacyContextWarning.forEach is not a function" while working with my project. This issue seems to have occurred after adding a script to the index.html file. Can anyone provide guida ...

Tips for preventing Django template from showing up prior to VueJS rendering

I am currently facing an issue with rendering a Django template using VueJs through CDN. Upon loading the page, I notice that the raw Django code is displayed initially before being rendered by VueJs, which typically takes less than a second. To fetch dat ...

What's the best way to ensure uniform spacing between the list items in this slider?

When using appendTo, I've noticed that the spacing between items disappears. I've tried adjusting the padding-bottom and left properties with no success. Does anyone have a suggestion for how to fix this issue? I'm at a standstill. $(&a ...

What is the best way to refresh a partial view using the Jquery .load() function?

On my page, there is a partial view within the "Attachments" div that I need to reload. I've been trying to achieve this by using the following command: $('#attachments').load('@Url.Action("Attachments" "Transactions",new {id=1297})&a ...

JQuery's accordion with the heightStyle set to "fill" is causing a vertical scrollbar

I recently integrated the JQuery accordion effect into my website and specified the heightStyle: fill so that it would occupy the entire window. However, it seems to be taking up an additional 1 or 2 pixels, causing the vertical scroll bar to appear. I su ...