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

Tips on submitting an Array from a Textarea to mongoDB

I have a question regarding posting an array of serial numbers. When I try to post the serial numbers added in the textarea, they are posted as a single string. Here is my form: <form class="" id="serialsForm" action="/serialsnew" method="post"> &l ...

Ways to execute a function only once within setInterval

Hey there, I'm facing an issue with this... getSocketPerSecond = function () { Interval_PerSecond = setInterval(function () { $.ajax({ url: "/asset/ashx/GetSocket.ashx", type: "post", ...

Is it possible to swap out images using srcset attribute?

Currently, I am facing an issue regarding changing the img on mobile and tablet devices to display different images. As a beginner with jQuery, I couldn't resolve it using that framework, so I am exploring options with html5. I am wondering if there ...

Managed the double-click event to select Snap.svg text

I am currently utilizing the snapsvg library for a project where I am implementing the dblclick event to trigger a browser window alert. However, when clicking on the svg canvas, not only does the alert pop up but some text on the canvas also gets selected ...

Grouping JavaScript nested properties by keys

I have a specific object structure in my code that I need to work with: { "changeRequest": [{ "acrId": 11, "ccrId": "", "message": "test message" }, ...

Error message signaling that the dollar sign symbol is not defined in the Laravel framework

Hello there, I'm currently learning Laravel and following a tutorial on building a student CMS. I have integrated a datepicker and a bootstrap modal that are supposed to pop up when clicking form buttons. However, despite everything appearing correct, ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

Showing the incorrect ziggy package

After successfully setting up the tightenco/ziggy package as per the documentation, I encountered an issue with the template displaying the entire list of addresses. Please help me identify where I may have made a mistake. <head> @routes ...

What are the steps to send AJAX data before closing the page?

Trying for over 7 hours to send a value to the database when the user closes the page, like online and offline. Still struggling to find a working solution. <script tysssspe="text/javascript"> //ST window.onbeforeunload = function(){ var user_st = ...

Struggling to retrieve JSON information from the database using AJAX

I am facing a challenge when it comes to fetching data from my database using these technologies. Here is the current scenario: var username = $('#username').val(); var password = $('#password').val(); // This IP is just an example fo ...

Encountering a 404 error when typing a link and refreshing the page in Laravel combined with VueJS

I encountered an issue while working on a Laravel VueJS application for our Proof of Concept (POC). I have integrated vue-router into the project and it is functional. However, whenever I attempt to navigate to a specific page defined in the routes of app. ...

Vue Components for managing relationships between parents and children

Is there a way to retrieve all Parent-Child relationships of Vue Components within a project? Whether through the command line or using console.log. Expected result: ├── rootpage │ ├── componentA │ │ ├── componentD │ ...

How to implement a self-invoking function in React JS like you would in regular JavaScript?

Is it possible to invoke the function good without triggering it from an event? I want it to run as soon as the page loads, similar to a self-invoking JavaScript function. Check out this example import React from 'react'; class App extends Reac ...

Acquire the current audio video stream directly from the web browser

Currently, I am utilizing a JavaScript library that internally invokes getUserMedia. My objective is to access the stream object that has already been initiated. Unfortunately, the library does not provide any means to retrieve it. Is there a method avai ...

Is it advisable to substitute setTimeout with node-schedule in a node.js environment?

How can I prevent players from entering a raffle between 11:55pm - 11:59pm every Thursday? I attempted to use node-schedule to block access during this time frame by scheduling it to run every second, but unfortunately, I was still able to access the route ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Ways to access an Environment variable within VueJs components

Seeking assistance from anyone. I'm trying to figure out how to access an environment variable that's stored in the .env file of a Laravel project from within a vuejs component. .env file SECREAT_KEY=<My secreat key here> I need to retr ...

Tips for maintaining focus while tabbing in a contenteditable field?

Why does the table lose focus every time I press tab instead of inserting a white space? How can I change this so that pressing tab just inserts a regular tab space? ...

Arrange records in ascending order by phone number when multiple are returned on the same date

Currently, I am working on an Angular application that is designed to keep track of tuxedo rentals. The main feature of the app is a table that displays information from an array stored in the controller. The initial task I completed was listing the items ...

What could be preventing this bootstrap carousel slider from transitioning smoothly?

I've created a CodePen with what I thought was a functional slider, but for some reason, the JavaScript isn't working. The setup includes bootstrap.css, jquery.js, and bootstrap.js. I'm having trouble pinpointing what's missing that&apo ...