Vue component input form not providing expected result

Here is the code snippet for my "ecedata" component with an input field:

<template>
    <div class="col-l-4">
        <p style="text-align: center">Data/day (GB)</p>
        <div class="form-input-set" style="background: white">
            <input v-bind:value="dataday" v-on:change="$emit('changedataday', $event.target.value)" type="number" class="form-input">
        </div>
    </div>
</template>

<script>
export default {
    name:"ecedata" ,
    props: {
        dataday:Number,
    },
    data () {
      return {

      }
    },

}
</script>

This component is being called in the main app.vue like this:

<template>
    <ecedata v-bind:dataday="dataday" v-on:changedataday="vuedataday" ></ecedata>
</template>

<script>
  import ecedata from '@/components/ece/data/ecedata.vue'

  export default {
    name: 'app',
    components: {
      ecedata,
    },
    data () {
      return {
          dataday:0,
      }
    },
    methods: {
      vuedataday() {
        alert(this.dataday)
      }
    },

  };

</script>

I've noticed that it always returns a value of 0 on input. Can you help me figure out what's causing this issue?

Answer №1

You successfully linked the value from the parent to the child component.

You were on the right track by connecting the vuedataday method as a callback for the changedataday event, which allows the function to receive the value passed through the event.

vuedataday(newDataday) {
    this.dataday = newDataday;
}

Another method for achieving two-way binding is by using v-model.

<ecedata v-model="dataday"></ecedata>

In the child component:

<input v-bind:value="dataday" v-on:change="$emit('input', $event.target.value)" type="number" class="form-input">

Learn more about Using v-model on Components in Vue.js documentation

Answer №2

In the parent component, you set the state but do not modify it. The event emits the updated value, however, your onChange function does not utilize it.

It is important to incorporate the passed value and make changes to the parent's state accordingly.

updateParentState(value) {
  this.dataday = value;
  alert(this.dataday)
}

Answer №3

It's advisable to utilize the @input event rather than the @change event. With the @input event, you can invoke a function that allows you to then use $emit on the parent method.

Your code should be structured as follows:

<template>
    <div class="col-l-4">
        <p style="text-align: center">Data/day (GB)</p>
        <div class="form-input-set" style="background: white">
            <input v-model="propsdata" @input="getValue" type="number" class="form-input">
        </div>
    </div>
</template>

<script>
export default {
    name:"ecedata" ,
    props: {
        dataday:Number,
    },
    data () {
      return {
         propsdata: this.dataday
      }
    },

    methods: {
       getValue() {
        this.$emit('changedataday', this.propsdata);
     }
   }
}
</script>

Make sure to use v-model for input binding and define a props variable to assign values in the child component. This coding practice is recommended for working with vue.js. Thank you.

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

The "Read more" feature is not functional on mobile devices

I am encountering issues with my Wordpress blog on mobile screens. The "read more" button is not functioning, and the screen size does not fit properly on mobile devices. Visit abood250.com for more information. CSS Styling: /* =Global ----------------- ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

Switching class names on click in Vue.js

When clicked, I would like to toggle the class name from "product fav" to "product fav active". The change should be conditional; if the class is already active, it should be removed. ...

Ways to convert asynchronous operations of Node.js into synchronous operations in Node.js

Using node js, I am making multiple AWS API calls within a for loop. var prodAdvOptions = { host : "webservices.amazon.in", region : "IN", version : "2013-08-01", path : "/onca/xml" }; prodAdv = aws.createProdAdvCli ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

How many logical lines of code are in the Ubuntu operating system?

As I develop my web application, it is crucial for me to track the lines of code written in languages such as php, css, html, and JavaScript specific to the /var/www directory. However, when using the command line code counter tool, I find myself tempted ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...

Tips for updating JS and CSS links for static site deployment

As I develop my static site using HTML files served from a simple web server, I want to use local, non-minified versions of Javascript code and CSS files. However, when it comes time to deploy the site, I would like to refer to minified versions of these s ...

Angular routes are failing to update the view even after attempting to refresh

I am facing an issue while trying to develop an angular app where the child state is not loading properly. app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('home& ...

Utilizing a window.onload function in Microsoft Edge

After trying to run some code post-loading and rendering on the target page, I was recommended to use the Window.load function. This method worked flawlessly in Firefox and Chrome, but unfortunately, I couldn't get it to function in IE. Is there an al ...

What is the best way to prevent a directory containing mock files from being included in a webpack build using vue.config.js?

In the root directory, I have a folder named mock that contains mock data used for running the app in development mode. However, when I build the app for production using vue-cli-service build, this folder gets included in the bundle, which increases the s ...

`Dealing with Java Servlet Exception in Kendo UI Environment`

I am facing an issue with displaying date in my Kendo UI grid. The data is coming from a Java servlet, and I have set the status code to 500 whenever an error occurs. Although I can see the error on the console, I am unable to handle it in JavaScript. My g ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

How can I open the Ion-datetime view for the current year without allowing the selection of a specific day?

I am currently troubleshooting an issue with an Ionic date-time picker component. Upon opening the datepicker, it defaults to showing May 2021. As I scroll to the present date, I notice a circle highlighting today's date indicating that it selects th ...

What steps are involved in integrating QuickBlox on your website?

I am completely new to web development and have a question about integrating QuickBlox into my website using JavaScript. I have included the necessary JavaScript files in my website and set up the QuickBlox admin application, but I'm not sure how to p ...

Is there a Facebook application embedded in the user's wall?

Is it feasible to create a website similar to YouTube, where users can share it on Facebook and run the app (in this case, the video player) directly on their wall without having to visit the YouTube page? If it is possible, is this functionality limited ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...

The update feature activates upon reaching the bottom of the page, but it continues to refresh constantly

In my VueJS component, I have implemented a scroll event that triggers an AJAX call to update the Jobs() function when the user is getting close to the end of the page. if ( windowScrollTop >= (documentHeight - windowHeight - 50) ) { this.updat ...

"Attempting to use push inside an if statement does not function as expected

The code snippet provided is causing an issue where `items.push` is not functioning correctly within the `if` statement. Interestingly, if you uncomment the line just before the closing brace `}`, then `items.push` works as intended. for (i = 0; i < ...

CSS :contains selector after adding a script through Ajax append operation

Is there a way to change the text color in $('td:contains("text")').css('color','red') after an Ajax load script? Here is the main code snippet <div id="datatable"></div> <script src="https://code.jquery.com/j ...