Utilizing Parent Method in VueJS Component: A Step-by-Step Guide

I need to access methods of the parent component from within the current one, without using props.

Below is the structure in HTML:

<div id="el">
    <user v-for="user in users" :item="user"></user>
</div>

And here is the Vue code snippet:

var usersData = [
    { id:1, firstname:'John', lastname: 'Doe' },
    { id:2, firstname:'Martin', lastname: 'Bust' }
];

var vm = new Vue({
    el: '#el',
    data: { users: usersData },
    methods: {
        getFullName: function (user) {
            return user.id + '. ' + user.firstname + ' ' + user.lastname;
        }
    },
    components: {
        user: {
            template: '<span>{{ fullName }}</span>',
            props: ['item'],
            computed: {
                fullName: function(){
                    return this.$parent.getFullName(this.item);
                }
            },
        }
    }
});

This specific VueJS version being used is 2.0.2.

Attempts like

this.$parent.$options.methods.getFullName()
and
this.$parent.methods.getFullName()
have not been successful in accessing the desired method.

Answer №1

To utilize dependency injection in Vue.js version 2.2.0+, you can make use of the inject and provide methods as shown below:

Sample HTML:

<div id="el">
    <user v-for="user in users" :item="user"></user>
</div>

JavaScript Code:

var usersData = [
    { id:1, firstname:'John', lastname: 'Doe' },
    { id:2, firstname:'Martin', lastname: 'Bust' }
];

var vm = new Vue({
    el: '#el',
    data: { users: usersData },
    methods: {
        getFullName: function (user) {
            return user.id + '. ' + user.firstname + ' ' + user.lastname;
        }
    },
    provide: function () {
        return {
            getFullName: this.getFullName
        }
    },
    components: {
        user: {
            template: '<span>{{ fullName }}</span>',
            inject: ['getFullName'],
            props: ['item'],
            computed: {
                fullName: function(){
                    return this.getFullName(this.item);
                }
            },
        }
    }
});

Live Example: https://jsfiddle.net/haaiee/v1ahoytm/2/

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

Using React.js to Retrieve Data from the Server without AJAX Calls

Currently, I am in the process of creating a web application using Express.js for the back-end and React.js for the front-end. Prior to using React.js, I utilized EJS templating and followed a similar workflow on the back-end as shown below: var express = ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

Utilize Angular's ng-repeat directive to iterate through this JSON data structure for implementing user-to

Struggling with the user-to-user messaging interface on an app and having difficulty using ng-repeat on the items. Here is the provided data: { "ID": 4118, "CreatedDate": "2015-08-20T03:12:50.397", "recipient": [ { ...

Incorrect media type linked to Gmail API attachment error

I need help sending a message via the Gmail API in JavaScript, including a JPEG file attachment. My code so far looks like this: $.ajax({ type: "POST", url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart", he ...

Deliver an assured result to a variable within the angular.extend() function

Can someone provide guidance on how to set myVar to a value returned from an asynchronous service method in the following example? angular.extend(this, { myVar: (function() { getVal(); })() }); function getVal() { var d = $q.defer(); ...

Comparing form submission with a button click to pass data using Ajax - success in one method but failure in the other

I am facing an issue with two pieces of jquery code in my Flask application. While one works perfectly, the other is not functioning as expected. Both the form and a button trigger the same function through ajax calls. Currently, for troubleshooting purpos ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

Top strategy for monitoring a user's advancement in reading different text segments

If you are familiar with zyBooks, I am looking to implement a similar feature where users can track the sections they have read and mark them as completed with a button. However, I am struggling conceptually with determining how best to structure my mongo ...

Angular ngView not displaying content on the page

To load a ngView page by clicking on a link, the html file does not appear as expected. Running the application directly without using localhost might be causing the issue. I simply opened index.html with Chrome browser, so it's possible that there i ...

The download handler (php code) is being triggered multiple times within a single request

My PHP script is responsible for handling download requests. Clients can access this script using a GET request, as shown in the Javascript example below: if (true) { window.open('/download?mode=paper&fid=' + fid, '_blank'); re ...

Can you pinpoint the weak wiring in this AngularJS function?

I am currently studying AngularJS and I suspect there may be a glitch in my page. On the page, there is a TEXTAREA where I have typed 'aaa'. The TEXTAREA is linked to an ng-model named input. The following AngularJS code aims to monitor external ...

Display the dialog box whenever a user hovers over an element in a Vuet

I am having an issue with displaying an edit button and opening a dialog box on click using mouseenter and mouseleave events. When I hover over the edit button, it is displayed, but as soon as I click on it, it disappears. Can anyone help me understand w ...

Issue with Laravel - JavaScript not functioning properly following the passage of a parameter through the route

I am currently working on a website that will display search results from various e-marketplaces. Everything was going smoothly with the JavaScript implementation until I attempted to pass parameters through the route. Once I did that, the results stopped ...

Leveraging useEffect and useContext during data retrieval

I'm currently in the process of learning how to utilize React's Context API and Hooks while working on a project that involves using fetch(). Although I am able to make the request successfully, I encounter an issue where I can't retrieve t ...

Can anyone explain why I am having trouble loading JavaScript files into a different HTML file?

Currently, I am developing an electron application. In my index.html file, I have successfully loaded JavaScript files in the head tag and can access the JS functions without any problems. Now, I have created a separate browser window with another HTML fi ...

Assign the input text field's value programmatically in the code-behind of a C# Asp.net application

I am attempting to change the value of an HTML input field from C# code behind. These inputs are created through a JavaScript loop, so I have not had much success using run at server or assigning values through <%= %>. Below is my script: var mytab ...

Delayed execution of Ajax request

Currently watching a Youtube video that explains the Call Stack and Event loop when dealing with Async events like Ajax calls. According to the video, JavaScript execution occurs line by line. Let's try running a sample program: var xhttp = new XMLHt ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

Leveraging a direct SQL query in conjunction with Sequelize ORM and the literal method

Seeking guidance on updating the field level_id in Sequelize ORM, linked to a foreign key in a table named level_tbl. select * from level_tbl; +----------+----------+ | level_id | Level | +----------+----------+ | 1 | Higher | | 2 | Or ...

The Google Maps API has been successfully initialized, however, it is experiencing difficulties being displayed on the webpage

I have been successfully using a custom Google API on various web pages. However, I encountered an issue where the map API loads successfully but is not displaying on a specific web page. Below are the relevant code snippets: <html> <head> &l ...