Learning how to obtain data in Vue.js controllers from a parent component, calculate new variables, and display them dynamically

https://i.sstatic.net/h6uDD.png

I am working on two components: CreditForm.vue and InformationBlock.vue

<template>
    <form class="parent">
        <div>
            <div class="form-group">
                <label for="property_value">property_value</label>
                <input type="number" class="form-control" id="property_value" v-model.number="property_value">
            </div>

            <div class="form-group">
                <label for="initial_fee">initial_fee</label>
                <input type="number" class="form-control" id="initial_fee" 
                       v-model.number="initial_fee">
            </div>

            <div class="form-group">
                <label for="credit_term">credit_term</label>
                <input type="number" class="form-control" id="credit_term" 
                       v-model.number="credit_term">
            </div>

            <div class="form-group">
                <label for="interest_rate">interest_rate</label>
                <input type="number" class="form-control" id="interest_rate" 
                       v-model.number="interest_rate">
            </div>
            
            <div class="d-inline-flex">
                <b-button @click="save">Save</b-button>
                <b-button @click="clear">Clear</b-button>
            </div>
            
        </div>
        
        <information-block :property_value="property_value"
                           :initial_fee="initial_fee"
                           :credit_term="credit_term"
                           :interest_rate="interest_rate"/>
                           
    </form>
    
</template>

<script>
    import InformationBlock from "@/components/InformationBlock";

    export default {
        name: "CreditForm",
        components: {InformationBlock},
        data() {
            return {
                property_value: 0,
                initial_fee: 0,
                credit_term: 0,
                interest_rate: 0
            }
        },
        methods: {
            save: function () {

            },
            clear: function () {
                this.property_value = 0
                this.initial_fee = 0
                this.credit_term = 0
                this.interest_rate = 0
            }
        }
    }
</script>

Another component includes:

<template>
    <div>
        {{property_value}}
        {{initial_fee}}
        {{credit_term}}
        {{interest_rate}}
        <table class="inner table table-borderless">
            <tr>
                <td>
                    <div>
                        <h5>month_pay</h5>
                        <h1>{{month_pay}}</h1>
                    </div>
                </td>
                <td>
                    <div>
                        <h5>income</h5>
                        <h1>{{income}}</h1>
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div>
                        <h5>overpayment</h5>
                        <h1>{{overpayment}}</h1>
                    </div>
                </td>
                <td>
                    <div>
                        <h5>loan_body</h5>
                        <h1>{{loan_body}}</h1>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</template>

<script>
    export default {
        name: "InformationBlock",
        props: {
            property_value: {
                required: true,
            },
            initial_fee: {
                required: true,
            },
            credit_term: {
                required: true,
            },
            interest_rate: {
                required: true,
            }
        },
        data: function () {
            let loan_body = this.property_value-this.initial_fee
            let t = this.interest_rate/1200
            let month_pay = Math.round(loan_body*(t + t/(Math.pow((1+t), this.credit_term*12)-1)))
            let income = Math.round(5 * month_pay/3)
            let overpayment = Math.round(month_pay*this.credit_term*12-this.property_value+this.initial_fee)
            return {
                loan_body,
                income,
                overpayment,
                month_pay
            }
        }
    }
</script>

In the child component, I aim to retrieve 4 variables from the parent, perform calculations, and display new variables reactively as each input changes. However, something seems off in my implementation of this feature. Can anyone offer some guidance or assistance?

Answer №1

One way to optimize your Vue component is by converting your data properties into computed properties. Computed properties automatically update when any of their dependencies (such as incoming props) change:

// InformationBlock.vue
export default {
    props: {/*...*/},

    // data: function () {
    //     let loan_body = this.property_value-this.initial_fee
    //     let t = this.interest_rate/1200
    //     let month_pay = Math.round(loan_body*(t + t/(Math.pow((1+t), this.credit_term*12)-1)))
    //     let income = Math.round(5 * month_pay/3)
    //     let overpayment = Math.round(month_pay*this.credit_term*12-this.property_value+this.initial_fee)
    //     return {
    //         loan_body,
    //         income,
    //         overpayment,
    //         month_pay
    //     }
    // },

    computed: {
        load_body() {
            return this.property_value - this.initial_fee
        },
        income() {
            return Math.round(5 * this.month_pay/3)
        },
        overpayment() {
            return Math.round(this.month_pay * this.credit_term * 12 - this.property_value + this.initial_fee)
        },
        month_pay() {
            let t = this.interest_rate/1200
            return Math.round(this.loan_body*(t + t/(Math.pow((1+t), this.credit_term*12)-1)))
        }
    }
}

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

Is there a way to ensure that the elements created by the select form are only generated once?

I have a JavaScript function that dynamically creates paragraph and input elements based on user selection in HTML. However, I am looking to optimize the code so that each element is only created once. Snippet of JavaScript code: function comFunction(sel ...

Serializing Form Data with Checkbox Array

I am currently utilizing JQuery to submit a form using the form.serialize method. However, within the same form, there is an array of checkboxes that are dynamically created by a PHP function. Here is the structure of the form: <form class="form" id="f ...

Unable to invoke parent method from child component in Vue causing issue

I am facing an issue where I am trying to trigger a method in the parent component from the child component using $emit, but for some reason, it is not working as expected. Can someone please help me troubleshoot this problem? Parent Component <templat ...

What are some ways to improve performance in JavaScript?

Can you help me determine which approach would be more efficient - using native functions of the language that involve 2 iterations or a simple for loop? The goal is to locate the index in an array of objects where the property filterId matches a specific ...

Using a Javascript hyperlink to trigger a POST request in Python

I am currently developing a web scraping and automation tool that requires the use of POST requests to submit form data. The final action involves using the following link: <a id="linkSaveDestination" href='javascript:WebForm_DoPostBackWithOptions ...

The Price Filtering feature in the MERN Stack for Products is currently experiencing technical difficulties

Hey there! I am currently working on developing an Ecommerce Application using the MERN Stack with redux. I've encountered a problem while trying to send a price array argument in my fetching function. The error message states: XHR GET http://localhos ...

How can you typically verify the type of an object variable in TypeScript?

How can I verify if the obj variable contains all the properties defined in the Person interface? interface Person { name: string; age: number; } const jsonObj = `{ name: "John Doe", age: 30, }`; const obj: Person = JSON.parse(jsonObj); ...

What is the reason behind the warning "Function components cannot be given refs" when using a custom input component?

When attempting to customize the input component using MUI's InputUnstyled component (or any other unstyled component like SwitchUnstyled, SelectUnstyled, etc.), a warning is triggered Warning: Function components cannot be given refs. Attempts to acc ...

How can I hide the drawer in Vuetify?

After adding navigation to the drawer, I encountered an issue where the drawer remains open when clicking on a link that goes to the same page. This can be confusing for visitors as it doesn't indicate that they are already on the current page. I att ...

Is it possible for me to nest a Firebase collection within another collection?

When gathering user information and favorite foods in a form, I'd like the favorite food data to be nested under the 'users' collection as Likes: const sendPosts = (e) => { e.preventDefault() db.collection("users").add({ ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

In order to develop a JS class in React JS, I must import Scripts

I have a collection of SDK scripts that need to be included in the following manner: <script src="../libs/async.min.js"></script> <script src="../libs/es6-shim.js"></script> <script src="../libs/websdk.client.bundle.min.js ...

Creating a loading spinner in a Vue component while using the POST method

After successfully creating a loader for fetching data using the GET method, I encountered challenges when attempting to do the same with POST method. Is there a reliable way to implement a loader during the POST data process? For GET method, I set the lo ...

Adjust the template loader settings to include additional parameters

Currently, I am focused on internationalization (i18n) of my Aurelia components. My goal is to render the translations server-side because our CMS houses the translations and they can be updated even after deployment. To achieve this, I have successfully d ...

Tips for selecting 'module' over 'main' in package.json

I have developed several npm modules and compiled them in two ways: commonJS (using exports.default =) and esm (using export default) In my package.json, I have specified the main file as index.cjs.js and the module file as index.esm.js. However, when ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

Using JavaScript to pre-select a radio button without any user interaction

Is there a way to programmatically set a radio button in a group without physically clicking on the button? I am attempting to open a jQuery page and depending on a stored value, the corresponding radio button should be selected. I have researched similar ...

Is it possible to make a form field inactive based on another input?

I need help with disabling certain form fields until other fields are filled in. You can check out an example of what I'm trying to achieve here: https://jsfiddle.net/fk8wLvbp/ <!-- Bootstrap docs: https://getbootstrap.com/docs --> <div ...

Transition effect for switching between pages with animated motion

I'm currently facing challenges in implementing page transition animations on my website. Can someone assist me with this? Here is the JavaScript code I have for animation (fading out the login form when the login button is clicked): <?php sessio ...

What is the best way to automatically scroll to the bottom of a modal after making a request and

I've been faced with a challenge regarding an online chat widget. My goal is to automatically scroll the widget down to display the latest message when a specific chat is opened. Despite using an async function, I encountered difficulties in achieving ...