The challenge lies in updating props using the `onchange` event in Vue.js 2

I am facing an issue with updating the data when using on-change from the select box. Initially, I can update the data by clicking a button or triggering the on-change event once. However, I encounter difficulties in updating the data multiple times through the on-change event.

    <template>
    <div>
        <div class="row">
            <select v-model="selectedemp" @change="filterempdata($event.target.value)">
                <option value="">Select Employee</option>
                <option v-for="option in empfilterlist" v-bind:value="option.value" v-bind:key="option.value">{{ option.text }}</option>
            </select>
        </div>
        <div class="row">
            <empView v-if='loaded' :empDetails='empData'></empView>
        </div>
        <div class="col-lg-6 col-md-6">
            <button type="button" id="btn2" class="btn btn-danger btn-md" v-on:click="getEmpDetails">Fetch Data</button>
        </div>
    </div>
</template>

Javascript section:

    data () {
      return {
        loaded: false,
        empData: {},
        empfilterlist: [
            { text: 'Department', value: '1' },
            { text: 'Status', value: '2' },
        ],
        selectedemp: '',
    }
},
methods: {
    filterempdata: function (selectedoption) {
        console.log('Onchange value - ' + selectedOption)
        Vue.set(this.empData, 'Department', selectedoption)
    },

    getEmpDetails: function () {
        this.$http.get('http://localhost:7070/getemmdata')
            .then((response) => {
            this.empData = response.data
            this.loaded = true
        },
        response => {
            console.log('test' + JSON.stringify(response))
        }
    )   
}

Child component javascript code:

    export default {
    name: 'empView',
    props: ['empDetails'],
    data () {
        return {
            empid: this.empDetails.id,
            empname: this.empDetails.name
        }
    },
    watch: {
        empDetails: function (changes) {
            console.log('data updated ' + JSON.stringify(changes))
            this.empid = changes.id
            this.empname = changes.name
            this.department = changes.Department
        }
    }
}

Answer №1

Your code seems to be missing some parts. I have made some edits and provided a small sample for reference. In your code, you are calling

Vue.set(this.empData, 'Department', value);
. It appears that there might be a spelling error as this.empData cannot be found.

UPDATE: Please avoid using camelCase in your html attributes (Try using :empdetails instead of :empDetails). I have removed the onchange attribute and replaced it with computed values.

const empview = {
  name: 'empview',
  template: '<div>ID: {{empid}} TITLE: {{empname}} RANDNUM: {{random}}</div>',
  props: ['empdetails'],
  computed: {
    empid() {
      return this.empdetails.id;
    },
    empname() {
      return this.empdetails.name;
    },
    random() {
      return this.empdetails.random;
    }
  },
  watch: {
    workflowDetails(changes) {
      console.log('data updated ' + JSON.stringify(changes))
      this.empid = changes.id
      this.empname = changes.name
      this.department = changes.Department
    }
  }
};


new Vue({
  el: '#app',
  components: {
    empview
  },
  data() {
    return {
      loaded: false,
      empData: {},
      empfilterlist: [
        { 
          text: 'Department', 
          value: '1' 
        },
        { 
          text: 'Status', 
          value: '2' 
        }
      ],
      selectedemp: ''
    }
  },
  watch: {
    // triggers on change
    selectedemp(value) {
      // your filterempdata() code
      console.log(value);
    }
  },
  methods: {
    /*getEmpDetails() {
      this.$http.get('http://localhost:7070/getemmdata')
        .then((response) => {

        this.empData = response.data
        this.loaded = true
      }, (response) => {
        console.log('test' + JSON.stringify(response))
      })
    }*/
    getEmpDetails() {
      console.log('getEmpDetails()');
      const data = this.empfilterlist.filter((emp) => emp.value == this.selectedemp)[0];

      if(data) {
        this.empData = {
          id: data.value,
          name: data.text,
          random: Math.random()
        };

        this.loaded = true;
      }
    }
  }
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>

<body class="container">

  <div id="app">
    <div>
      <div class="row">
        <select v-model="selectedemp">
          <option value="">Select emp</option>
          <option v-for="option in empfilterlist" :value="option.value" :key="option.value">{{option.text}}</option>
        </select>
      </div>
      <div class="row">
        <empview v-if='loaded' :empdetails='empData'></empview>
      </div>
      <div class="col-lg-6 col-md-6">
        <button type="button" id="btn2" class="btn btn-danger btn-md" @click="getEmpDetails">Fetch Data</button>
      </div>
    </div>
  </div>

<script src="https://vuejs.org/js/vue.js"></script>
</body>
</html>

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

Images cannot be uploaded using ajax

I have been troubleshooting an issue with uploading image files using ajax without refreshing the page. However, I am facing a problem where the file does not get moved to the specified folder even after implementing basic PHP code for file upload. if($_S ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

What is the correct way to trigger an event specified as a string parameter in the emit() function?

My current goal is to pass the emit name as a string (for example, 'showComponent') from child to parent. I then want to trigger another emit in the emitAction(callbackName: string) function, and finally execute the showComponent() function. I&a ...

What is the most effective approach for returning varying object types based on conditions in JavaScript?

Currently, I am working on creating a function to validate input arguments. However, I am unsure if the method I am using is considered best practice. The validation function I have created looks like this: const isValidStudyId = (id) => { if (valida ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

React - Issue with state not being updated accurately

My current project involves using the <Select> component from Material-ui to create a drop-down menu. I need to update the state of the <Select> component after a selection has been made. To achieve this, I have set the value property of the & ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

Display an AJAX div when the image is hovered over and have it track the movement of

I am seeking assistance with my website project, which involves providing users with download links to movies. However, I am struggling to make the preview_block div(id) appear when the mouse hovers over the movie_block div(id). Additionally, I am having ...

I am encountering an issue where I am unable to send a HashMap String to a PHP server, and I am not receiving a JSONArray in the

How can I send a hashmap string to a PHP server without receiving back a JsonArray using Volley in Android? CM =$_POST['code_send']; $db =Db::getInstance(); $records = $db->query ("SELECT * FROM p_users WHERE c_meli='$CM'"); $js ...

Encountering difficulties with the functionality of Google Places API

I am attempting to incorporate the autocomplete functionality of Google Places API into a text field. Below is the code I have implemented: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script ...

jwplayer - track viewing time - monetize by the minute - trigger action based on duration

My goal is to track the time duration that someone watches a video, ideally by triggering an action every minute. I'm aiming to create a pay-per-minute system where a credit is withdrawn from the user for each minute they watch. If this setup isn&apo ...

Creating a collection of interconnected strings with various combinations and mixed orders

I am currently working on creating a cognitive experiment for a professor using jsPsych. The experiment involves around 200 logical statements in the format T ∧ F ∨ T with 4 different spacing variations. My main challenge is to figure out a way to a ...

The Google Maps geocoding service fails to provide accurate location information

I am currently attempting to utilize the Google Maps Geocoding API within my JavaScript code. Below is the snippet I have written: var geocoder = new google.maps.Geocoder(); function geocodeAddress() { var address = document.getElementById("address").v ...

Having trouble syncing a controller with AngularJS

Despite numerous attempts, I am still struggling to make a single controller function properly. Lately, I've been working on Angular projects and no matter what I do, my controllers just won't cooperate. In my latest project, everything is withi ...

Having trouble establishing a connection to MySQL through NodeJS and Express

I am currently attempting to establish a connection to MySQL using a nodeJS app with express as the server. I have referred to the mysql npm documentation to start the connection process, but I keep encountering an error in the callback function within cre ...

Seeking assistance in optimizing my Javascript code for more efficient canvas rendering

I've created a script for generating random moving lines as a background element for my portfolio. While it runs smoothly on its own, I encounter frame drops when combining it with other CSS animations and effects, especially at the beginning (althoug ...

Despite encountering an error in my Vue page, my project is still up and running smoothly

[Vue alert]: The provide function is being called without an active component instance to be associated with. Lifecycle injection APIs can only be accessed while executing the setup() method. ...

Mapping JSONP responses for jQuery UI autocomplete

Attempting to implement jqueryUI autocomplete. After alerting the response, it shows: ([ { "id": "test", "label": "test", "value": "test" } ]); However, when trying to map the result, the dropdown remains empty. Here is the code being used: <script> ...

What is causing the error that app.js file cannot be located?

Here is the layout of my directory: ReactCourse // Main folder public // Subfolder within ReactCourse index.html // HTML file with linked js file app.js // JavaScript file This is the content of index.html: <!DOCTYPE ...

Conceal any elements designated by a particular class and reveal them based on their corresponding ID

I have utilized jQuery's hide() function to initially hide all elements of a specific class when the page loads. My goal is to make individual elements visible again based on their unique IDs when a corresponding link is clicked. In total, there are ...