What is the best way to access a component's value from a different component in Vue script?

I have two Vue components in my PHP file: "application" and "vn" component. I am trying to fetch {{obj.vacancies_left}} from the "vn" component and use it in the "application" component. However, I keep getting an undefined variable error. I attempted to retrieve it using getElementById but it still returns as undefined.

Application Vue Component

var application = new Vue({
    el: '#engineerlist',
    data: {
        engineer: [],
        allData: '',
        actionButton:'Enrol',
        courseID: '',
    },
    methods:{
        decreaseVacancy:function() {
            axios.post('http://localhost/admin/decreaseVacancies.php',{
                action:'delete',
                CourseID: '101'

            }).then(function(response){
                var vacancy = document.getElementById("vacanciesleft").value;
                console.log(vacancy);
                alert(response.data.status);

            }).catch(function(error) {
                console.log(error);
            });
            
        }
    } 
});

VN Vue Component

var vn= new Vue({
    el: '#courseInfo',
    data: {
        courses: []
    },
    created: function() {
        axios.get('http://localhost/SPM-Group-3/admin/getSoftware.php')
        .then(response => {
                return_objs = response.data
                for (obj of return_objs) {
                    this.courses.push(obj)
                }
            })
            .catch(error => {
                this.courses = [{ value: 'There was an error: ' + error.message }]
            })
    }
});

I want to access the {{obj.vacancies_left}} in the "application" Vue component's "decreaseVacancy" function.

<div v-for="obj in courses" v-bind:value="obj">
    <h2 class="title">{{obj.courseID}}</h2>
    <h3 class="title">{{obj.courseName}}</h3>
    <p class="text">{{obj.description}}</p>
    <b>Total vacancies: </b> {{obj.vacancies}}<br>
    <b ref="vacanciesleft">Number of vacancies left: </b> <span id="vacanciesleft">{{obj.vacancies_left}}</span>
</div>

Answer №1

Transferring data between Vue Components.

  • Parent -> Child. Sending data from Parent to Child can be done through the use of Props,
  • Child -> Parent. Passing data from Child to Parent is achievable by using Events with $emit('my-event'). Refer to Listening to Child Components Events
  • Unrelated components can communicate and share data utilizing Event Bus with this.$root.$emit.

If incorporating Vuex, it's considered the optimal method for exchanging data among unrelated components.

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

What steps can be taken to resolve the error message "AttributeError: 'WebElement' object does not have the attribute 'find_element_class_name'?"

try: main = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "main")) ) articles = main.find_elements_by_tag_name("article") for article in articles: header = article.find_element_c ...

Parsing Problem---Is there a Parsing Error?

My code includes a function that calculates the total of cells and then displays it in a textbox: function UpdateTotal() { var total = parseFloat('0.0'); $("#<%= gvParts.ClientID %>").find("tr").not(".tblResultsHeader").each(funct ...

Function utilizing variables parsed by Angular directive

I am currently working on a directive that I have created: feedBackModule.directive("responseCollection", ['deviceDetector', function (deviceDetector) { return { restrict: "E", templateUrl: 'js/modules/Feedback/direc ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

Ajax call encounters 404 error but successfully executes upon manual page refresh (F5)

I am encountering a frustrating issue with my javascript portal-like application (built on JPolite) where modules are loaded using the $.ajax jquery call. However, the initial request fails with a 404 error when a user first opens their browser. The app i ...

Adjust the text within the paragraph dynamically according to the option chosen in the drop-down menu using

I'm having trouble updating a paragraph in a letter based on the user's selection from a dropdown menu. I can't seem to figure it out. I don't know whether ng-show/hide or ng-options is the best approach for this. I feel completely los ...

Assigning a custom class to the cdk-overlay-pane within a mat-select component is restricted to Angular Material version 10.2.7

I attempted the code below, but it only works for angular material 11. My requirement is to use only angular material 10. providers: [ { provide: MAT_SELECT_CONFIG, useValue: { overlayPanelClass: 'customClass' } } ] There a ...

Error: Unable to access the toISOString property of an undefined object

import './ExpenseItem.css'; function ExpenseItem(props){ return ( <div className="expense-item"> <div>{props.date.toISOString()}</div> <div className="expense-item__description"> ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

Why isn't any of my AngularJS code running as expected?

I've recently started learning AngularJS, but I'm encountering an issue where none of my code is being executed when I run the page. Instead, all I see on the website is {{angular-message}} and I'm receiving the error "Error: [ng:areq] Argum ...

Can you explain the concept of a TransientTransactionError within Mongoose (or MongoDB)?

Two important files in my project are server.js and db.js. The db.js file is responsible for interacting with the database using Mongoose, while server.js calls functions from db.js: var mongoose = require('mongoose'); mongoose.connect('&ap ...

Retrieve the data from every dropdown menu

How can I retrieve the selected values from all created selects when a button is clicked? I have attempted using both refs and v-model, but neither of them are functioning as expected. <div v-for="attribute in attributes" class="col"> {{ a ...

What is the syntax for invoking a function within a nested function in TypeScript?

Is there a way to call the function func2 from within the sample function of function func1? Any suggestions on how to achieve that? class A { public func1() { let sample = function() { //call func2... but ...

Examining an Array of Objects Based on Various Attributes

Looking to find a way to check if a similar object already exists in an array of objects. Specifically, I want to know if there is an object with the same make and model properties (Ford Focus): { make: 'Ford', model: 'Focus', co ...

The Owl carousel animation fails to work in Chrome browser

I am currently customizing an HTML5 template that utilizes the Owl Carousel 1.3.2. My goal is to incorporate a smooth fade animation when transitioning between slider images. The code snippet below works perfectly in the Mozilla Browser, however, I'm ...

magnific popup: trigger the display by clicking on an element other than the image

A recent request from the client calls for the image caption to cover the thumbnail fully when hovered over. To meet this requirement, I now need to enable clicking on the caption to open Magnific Popup rather than using the <a> tag. Here is what I h ...

Updating the id token in VueJs using Axios interceptor when it expires

I need to implement an axios interceptor that will add the idToken as an authorization header to every axios call, and also refresh the idToken if it has expired before making any call. My current code for this task is as follows: axios.interceptors.requ ...

What is the method for integrating fingerprint recognition into a web application using either Laravel or Django?

For a school project, I've been tasked with creating a web application that can fingerprint users or visitors. This means gathering details about their device such as OS, browser, IP address, country, city, and more. The app needs to be modern and re ...

Using Javascript, display an image that was previously hidden with CSS when a radio button is selected

Within a table of 25 rows, each row contains an attribute accompanied by an image (represented by a tick symbol) and five radio buttons for rating the attribute from 1 to 5. Upon clicking one of the radio buttons, the hidden image (tick symbol) should beco ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...