The process of altering a property in input data within Vue.js

I have a component called Input.vue that displays a label and an input field of some type. Here is how it looks:

<template>
    <div class="form-element">
        <label :for="inputId" :class="['form-element-title', { 'js-focused': focused }]">{{ label }}</label>
        <input :disabled="!canEdit" :type="inputType" :id="inputId" :name="inputName" v-model="inputData" :placeholder="placeholder" @focus="focused = true" @blur="focused = false">
    </div>
</template>

<script lang="ts">
    import { Component, Prop, Vue } from 'vue-property-decorator';

    @Component
    export default class Input extends Vue {
        @Prop({ default: () => {} }) inputId!: string
        @Prop({ default: () => {} }) inputType!: string
        @Prop({ default: () => {} }) inputName!: string
        @Prop({ default: () => {} }) label!: string
        @Prop({ default: () => {} }) placeholder!: string
        @Prop({ default: () => {} }) data!: string
        @Prop({ default: () => true }) canEdit!: boolean

        private inputData = this.data;
        private focused = false
    }
</script>

Another component calls it like this:

<input-component inputId="formDiscountName"
                 inputType="text"
                 inputName="discountName"
                 :label="translations['name']"
                 :placeholder="translations['name']"
                 :data="discount.name"
/>

The issue arises when entering data in the input field - discount.name does not update because it's instantly assigned to the inputData variable inside the input-component and the data property doesn't reflect the change. Since mutating the data property directly is not recommended due to Vue warnings, I explored using computed properties but unsure of the proper implementation.

One solution could be to use a computed property and emit an update within the set function:

get inputData() {
    return this.data;
}

set inputData(value: string) {
    this.$root.$emit('inputUpdate', {'inputName' : this.inputName, 'inputValue' : value});
}

However, emitting events may not be the most elegant solution. Are there any better alternatives?

Answer №1

To track changes in the inputData, you can set up a watcher. After that, there are several ways to update the discount name.

  1. You could emit the value of inputData from the watcher and create a handler in the parent component

Alternatively,

  1. If passing discount.name seems problematic for your use case, consider passing the entire discount object instead. Then, you can modify the name property of the object without triggering any warnings since it's just a property alteration.

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

Error: The manifest.json file is failing to load in production mode

Attempting to convert my Vue/Laravel application into a PWA has hit a snag. The issue I'm encountering is that my manifest.json file is not being linked to the head of my production build. While it works fine in development, the browser does not detec ...

Update the button text dynamically when clicked without using an identifier or a class

If we take a look at my button in the following code: <input type="button" value="BLUE" name="button_blue" /> My goal is to have the value="BLUE" changed to value="RED" or any other desired value when the button is clicked. ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...

JavaScript alert system

Seeking advice on a situation. Here's the scenario I'm facing: In a messaging platform, I have an array of users who are currently online. When a new user joins the chat, I want to notify the first user in the array. If there's no response w ...

Is nested testing the key to an elegant JQuery/AJAX form validation solution?

As I implement form validation with JQuery/AJAX, my goal is to provide a seamless experience for users. When an entry is missing or incorrect, I aim to display a single alert message and return the user to the form so they can make adjustments and resubmit ...

Tips for implementing a conditional statement within an export default clause

I am completely new to web programming and I'm attempting to create a question-answer feature using Vue.js. export default { // Trying to implement an if statement (if character == "Past", then do these steps) "steps": [ { ...

The post page remains out of reach for Ajax

I've been struggling for hours to identify the issue with this code. I realized that I am unable to access the updateuser.php file even though it is in the same directory and the filenames are correct. Can someone please review the code below and let ...

Having trouble getting nodeJS socket.io to function properly on my Raspberry Pi

Being new to nodeJS and programming, I've been trying to get this piece of code to function properly with no success. It's frustrating because I can't figure out why it's not working, and I am clueless on how to troubleshoot it. Despite ...

Delete dynamic elements from an array once they are no longer present in the DOM

In this code snippet, I have implemented a button that adds a new object to both the document and an array. When you click on each object, it gets removed from the document. However, the challenge here is how can we also remove it from the array? You can ...

Implementing CKEditor instances within AngularJS Controller scopes

Greetings everyone, Recently, I have been exploring Angular JS. Everything is going smoothly - my controllers, services, and so on. However, when attempting to make a Div editable that is within the ng-controller, the ckeditor toolbar fails to appear. On ...

Adding text in CKEditor with Angular while preserving the existing formatting

To add my merge field text at the current selection, I use this code: editor.model.change(writer => { var position = editor.model.document.selection.getFirstPosition(); // trying to connect with the last node position.stickiness = 'toP ...

Encountering a Problem with Image Rendering in Next.js

Issue: I am facing a problem while trying to display a react component using <Gallery images={images} />. The component itself is rendered, but the images from the array are not showing up initially. However, when I resize the screen by dragging the ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

What is the best way to streamline a state-dependent getter, with a focus on adhering to SOLID principles?

Is there a more user-friendly way to retrieve different data based on the type in my Angular component? I'm considering separating the component into two: one for phone and one for email. However, I'm concerned about duplicating most of the logi ...

Incorporating a MUI5 theme into a custom emotion-themed application

I'm currently working on an application that incorporates multiple themes. One of these is a Material UI theme specifically designed for MUI v4, while the other is an emotion theme used by non-MUI components. In my attempt to transition to MUI v5, I ...

Guide to creating a versatile bootstrap modal window in Vue.js

I need some assistance with creating a bootstrap modal window that provides a warning to the user before they take an action. The issue I am facing is that when I enter text into a field, close the modal, and then reopen it, the previous values are still t ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: htt ...

Executing API calls utilizing Axios in a NodeJS environment with the Authorization Basic feature

I have developed an API to retrieve a token from PayPal. curl -v POST https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "CLIENT_ID:SECRET" &b ...

Get the HTML source code for a form that has been created using AngularJS

Can AngularJS be used to download a portion of code generated by a form? Insert the following code snippet: http://jsbin.com/nufixiwali/edit?html,js,output I am looking to generate an .html file that only includes the code generated after the html tag. ...

Understanding the unpredictability of A-Sync in Node.js/Express: Why does it appear to operate in a non-linear fashion?

Recently, I delved into the world of Node.js/Express and encountered asynchronous calls that must complete before moving on. My code features three different endpoints that need to be hit. Considering the asynchronous nature, I attempted to structure my c ...