Guide on implementing a template within a form using Vue.js

I have set up a Vue instance for handling the form data

var formInstance =  new Vue({
    el: '#amount_form',
    data: {
        logdate: '',
        amount:'',
        description:''
    },
      methods: {
        processForm :function(event)
        {
            var formData = {"logdate":this.logdate,"amount":parseFloat(this.amount),"description":this.description};
            console.log(formData);

            var parameters =
                {
                    "data":formData,
                    "url":"save",
                    "type":"post",
                    "data_type":"JSON",
                    "callback":function(data)
                    {
                        alert(data);
                    }
                }
                sendDataToServer(parameters);
        }
    }
});

Additionally, I have created a template for categories selection

var categorySelect = Vue.component('category-select',
    {
        data()
        {
            return{
                options:[],
                cat:""
                }},
        template:'<select class="form-control form-control-sm" v-model="cat">' +
            '       <option v-for="option in options" v-bind:value="option.id">{{option.name}}</option></select>',
        created :function()
        {
            var templateObject = this;
            var parameters =
                    {

                        "url":"getCategories",
                        "type":"GET",
                        "async":true,
                        "data_type":"JSON",
                        "callback":function(data)
                        {
                            templateObject.options = data;
                        }
                    }
                sendDataToServer(parameters);
        }
    });

The template for categories is used within the form

    <div class="row">
                            <div class="col-3">
                                <div class="form-group">
                                    <label for="log_date" class="sr-only">Date</label>
                                    <input v-model="logdate" type="datetime-local" id="log_date" class="form-control form-control-sm" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="form-group">
                                    <label for="amount" class="sr-only">Amount</label>
                                    <input v-model="amount"  type="text" class="form-control form-control-sm" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="form-group">
                                    <label for="category" class="sr-only">Category</label>
                                    <category-select></category-select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class="form-group">
                                    <label  for="description" class="sr-only">Description</label>
                                    <textarea v-model="description" class="form-control" id="description" aria-label="With textarea"></textarea>
                                </div>
                            </div>
                        </div>
                        </form>

To retrieve the form values, you can refer to the submitted data processed by the 'processForm' method.

Answer №1

You have the ability to trigger an event from the child component. The parent component must be set up to listen for this custom event and extract the data from it. Additionally, you must have a listener for onChange on your select element to trigger the event.

The template structure for categories should resemble something like the following:

var categorySelect = Vue.component('category-select',
{
    data()
    {
        return {
            options:[],
            cat:""
        }
    },
    template:'<select class="form-control form-control-sm" v-model="cat" @change="handleUpdateSelectedValue($event)">' +
        '       <option v-for="option in options" v-bind:value="option.id">{{option.name}}</option></select>',
    methods: {
     handleUpdateSelectedValue(event) {
       this.$emit('selectedValue', event.target.value) // emitting the event here
     }
    }
    created :function()
    {
        var templateObject = this;
        var parameters =
                {

                    "url":"getCategories",
                    "type":"GET",
                    "async":true,
                    "data_type":"JSON",
                    "callback":function(data)
                    {
                        templateObject.options = data;
                    }
                }
            sendDataToServer(parameters);
    }
});

Furthermore, you need to listen for the event in the parent component as shown below:

<div class="col-3">
  <div class="form-group">
    <label for="category" class="sr-only">Category</label>
    <category-select @selectedValue="handleSelectedValue"></category-select>
  </div>
</div>

Lastly, you just need to define handleSelectedValue in your parent component and utilize the received value appropriately.

var formObject = new Vue({
 el: '#amount_form',
 data: {
    logdate: '',
    amount:'',
    description:''
 },
 methods: {
  handleSelectedValue(value) {
  }
 }
 ...

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

Limitations of GitHub's rate limiting are causing a delay in retrieving user commit history

I have developed a code snippet to retrieve the user's GitHub "streak" data, indicating how many consecutive days they have made commits. However, the current implementation uses recursion to send multiple requests to the GitHub API, causing rate-limi ...

Get the QR code canvas image with a customized background by downloading it

I am having trouble with downloading a QR code canvas image with a background. The download works fine, but my device is unable to scan the code properly due to an incomplete border. I need to add a white background behind it to make it larger. Current im ...

Is there a way for me to configure my website so that when a link is clicked, my PDF file will automatically open in Adobe

I've been facing an issue where I need my users to access a specific PDF file from a link on my website. Currently, the PDF opens in a separate tab next to my site, but ideally, I would like it to be forced to open in Adobe Reader directly. Is this ac ...

The Window.print() function may experience compatibility issues across different browsers

When attempting to utilize the Window.print() function, I encountered an issue where it works perfectly in Google Chrome but not in Mozilla Firefox. Attached are screenshots displaying the problem at hand. What could be causing this discrepancy? Furthermor ...

What is causing console.log to not work in Vue.js?

Environment $ node -v v8.16.2 $ npm -v 6.4.1 "vue": { "version": "2.5.16", "resolved": "https://registry.npmjs.org/vue/-/vue-2.5.16.tgz", "integrity": "sha512-..." }, "nuxt": { "version": "1.4.1", "resolv ...

Is there a way to incorporate onComplete and onAbort callbacks with <router-link> similar to router.push(location, onComplete?, onAbort?)?

It is common knowledge that the onComplete and onAbort optional callbacks can be used as the 2nd and 3rd arguments in the router.push method. router.push(location, onComplete?, onAbort?) These callbacks are triggered when the navigation is either success ...

Maximizing the worth of itemtype using jQuery: A guide

My goal is to include an 'itemtype' attribute in the body tag, body.page-body.ng-scope.device-lg(itemscope='', itemtype='') I attempted the following method $('body').add(itemtype='t1'); Unfortunately, ...

Is there a way to include text within a <v-progress-linear /> component in Vue.js using Vuetify?

Can text be inserted inside a v-progress-linear element? See the code sample below. If it is possible, how can this be achieved? <v-progress-linear background-color="pink lighten-3" color="pink lighten-1" value="15" > </v-progr ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

Retrieving Files from POST Request Body Using Node.js and Angular

Currently, I am developing a MEAN Stack application and facing an issue while handling a form that should allow users to upload a file upon submission. The process seems to work seamlessly on the client side; however, when I inspect the request body after ...

Applying scoped styling in Vue.js renders the SCSS ineffective

My SCSS code works perfectly on a simple page where I apply background-color. However, when I make the file scoped, the SCSS doesn't seem to have any effect. It's important for me to keep this component scoped so that the background-color doesn&a ...

Instructions for altering the hue of a canvas square when the cursor hovers over it

I want to implement a feature where the color of a tile changes when the user hovers their mouse over it, giving it a whitened effect. The tileset I am using consists of 32x32 tiles. Below are the scripts for reference. MAP.JS function Map(name) { ...

Implementing Vuejs sorting feature post rendering

Currently, I have elements linked to @click event listeners. <th @click="sort('dateadded')" class="created_at">Date Added I am looking for a way to automatically trigger this sorting function when the Vue.js component renders, so that th ...

The base64 code generated by the toDataURL method on the canvas appears to be incorrect

I am facing an issue with my code while using canvas to draw a cropped image with base 64. The problem is that it works perfectly on Chrome but gives me a blank image on Firefox. async function base64SquareCrop(imgbase64, size = 224) { const img = docume ...

JSF Ajax call: Invoking a JavaScript function at the completion

Working on a project with JSF 2.0, here is the form being used: <h:form id="fff" onsubmit="reloadMap();"> <h:selectOneMenu value="#{rentCarPoolBean.state}"> <f:selectItems value="#{rentCarPoolBean.stateList}" id="stateList" /> ...

Transforming a circular data structure into JSON format within Firebase

The data returned from firebase is causing an issue when I try to stringify it: JSON.stringify(data) // where data represents the returned object This results in the error: TypeError: Converting circular structure to JSON What is the correct way to hand ...

The angularJS ternary expression is not considered valid

{{var.a != "N/A" ? "<a ng-href='myapp://find?name="+var.a+"'>"+'var.a'+"</a>" :var.a}} The ternary operator I have used in this Angularjs format does not seem to be working correctly. In the view, the ternary result is not ...

Utilizing Angular 5: Enhancing ngFor with a Pipe and a Click Event

Iterating through an array of objects using *ngFor, I apply various filters via pipes to manipulate the resulting list. One of these pipes relies on a user input from a search field. Upon clicking on one of the ngFor elements, the corresponding object is p ...

The ng-show directive is failing to update properly after changes are made to the scope values

I'm experiencing some issues with the ng-show method. I have set it up like this: Even though the username string length is checked, the ng-show method doesn't seem to hide/show the extra text until after another keystroke. How can I make it upd ...

Need to import Vue from a JavaScript file

I am relatively new to modern frontend development tools. After installing Nodejs and NPM, I successfully downloaded packages such as "jquery" and everything was working fine. However, when I installed Webpack (version 2) and created a demo configuration f ...