0

I have 2 vue component in my PHP file: application and vn component. I want to get {{obj.vacancies_left}} from vn component and call it in application component. How should I do it? I keep getting undefined variable. I tried getting it by getElementById but it shows me undefined variable.

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 }]
            })
    }
});

This is the {{obj.vacancies_left}} that I want to retrieve in application vue component 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>

1 Answers1

0

Sharing data across Vue Components.

  • Parent -> Child. To pass data from Parent to Child you can use Props,
  • Child -> Parent. To pass data from Child to Parent you can use Events with $emit('my-event'). See Listening to Child Components Events
  • Unrelated components can also share data using Event Bus with this.$root.$emit.

If using Vuex, I'd say that is the best way to share data across unrelated components.

tony19
  • 125,647
  • 18
  • 229
  • 307
Pablo
  • 1,604
  • 16
  • 31
  • can I use event bus if my vue script is in PHP file? its not vue file – Pleasehelpme Nov 05 '21 at 03:08
  • You need to understand the difference between client and server. Check this Q&A https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming Your PHP code runs on the server. Your Vue "compiled" code runs on the client (Browser) – Pablo Nov 05 '21 at 07:21