Creating interactive functionality for textareas and input fields in Vue: A beginner's guide

I need assistance with creating a function where changing the input field will also automatically update the textarea's value. I have successfully implemented Vue js for updating the input field based on the textarea, but I am struggling to reverse this process. Any suggestions or solutions for this scenario would be greatly appreciated.

Textarea

<v-row>
    <v-col cols="12" sm="6">
        <v-textarea
            v-model="groupTask"
            dense
            :hide-details="true"
            outlined
            label="Group Task"
        ></v-textarea>
    </v-col>
</v-row>

input field

<v-row v-for="(item, index) in tasks">
    <v-col cols="12" sm="4">
        <v-text-field
            dense
            :hide-details="true"
            outlined
            :label="'Group Task Number ('+ (index+1) + ')'"
            :name="tasksList[index]"
            v-model="item.number"
        ></v-text-field>
    </v-col>
    <v-col cols="12" sm="4">
        <v-text-field
            dense
            :hide-details="true"
            outlined
            :label="'Group Task Name ('+ (index+1) + ')'"
            :name="tasksList[index]"
            v-model="item.task"
        ></v-text-field>
    </v-col>
    <v-col cols="12" sm="4">
        <v-text-field
            dense
            :hide-details="true"
            outlined
            :label="'Group Task Price ('+ (index+1) + ')'"
            :name="tasksList[index]"
            v-model="item.price"
        ></v-text-field>
    </v-col>
</v-row>

Vue Code

<script>
export default {
    data() {
        return {
            tasks: [],
            groupTask: "",
            tasksList: [],
        };
    },
    watch: {
        groupTask: function(newValue, oldValue) {
            let data = newValue.split("\n");
            let item = Math.ceil(newValue.split("\n").length / 3);
            this.tasks = [];
            for (var loop = 0; loop < item; loop++) {
                let tmp = data.slice(loop * 3, loop * 3 + 3);
                this.tasks.push({
                    number: tmp[0],
                    task: tmp[1],
                    price: tmp[2]
                });
            }
        },
    },
    computed: {},
    methods: {},
    created() {}
};
</script>

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

Answer №1

Utilizing getters and setters within a computed property allows for establishing interdependency between two variables.

No reliance on watchers is necessary.

export default {
  data() {
      return {
          tasks: [],
          tasksList: [],
      };
  },
  computed: {
    groupTask: {
      get() {
        return this.tasksList.map(task => [task.number, task.task, tast.price]).flat().join("\n"); // your reverse code to generate groupTask string from tasksList array here
      },
      set(newVal) {
        let data = newValue.split("\n");
            let item = Math.ceil(newValue.split("\n").length / 3);
            this.tasks = [];
            for (var loop = 0; loop < item; loop++) {
                let tmp = data.slice(loop * 3, loop * 3 + 3);
                this.tasks.push({
                    number: tmp[0],
                    task: tmp[1],
                    price: tmp[2]
                });
            }
      }
    }
  }

To delve deeper into computed properties and their getters and setters, refer to the following link: https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter

Answer №2

If you want to make the textarea readonly, you can use the computed property for groupTask or utilize item.task as the v-model for the textarea.

computed: {
    groupTask() {
        return item.task;
    }
}

Additionally, you can implement the following watch method for updating:

watch:{
     'item.task': (newVal, oldVal) => {
         this.groupTask = newVal;
     }
 }

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

When utilizing Axios to upload Base64 data, an [Errno 54] error may occur due to a connection

Currently, I am in the process of developing a web application using VueJS for the front-end and Django (Django Rest Framework) for the back-end. One of the key features of this application is the ability to send a PDF invoice via email. To achieve this, ...

Ensure that you wait for all asynchronous $http requests to finish in AngularJS before continuing

I am facing a challenge with a page that generates a varying number of $http requests based on the length of a certain variable. I aim to update the scope with the data only after all requests have been completed. Without relying on jQuery for this project ...

Triggering an error message when a user attempts to submit an incomplete angular form

Working on an Angular form where users advance to the next step by clicking a button, but it remains disabled until all fields are valid. I'm wondering how I can implement a custom class to highlight incomplete fields when the user tries to move to t ...

Combining Entities Using Immutable JavaScript

Currently utilizing React, Redux, and Immutable. I have a question about merging a plain JavaScript object into an Immutable Map object. Importing Immutable.js: import { List as iList, Map as iMap } from "immutable"; The content of action.paylo ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

Exploring the functionalities of radio buttons and arrays in a Javascript experiment

Currently delving into the world of Javascript and struggling to wrap my head around creating a test using only pure Javascript (no jQuery). The goal is to: Present users with a question and provide radio button options for selection. Allow users to cho ...

Tips for effectively reusing the modal component in Vue.js without encountering re-render issues

I'm encountering an issue where the same component content is being rendered despite having different components (Rendering problem). I have a reusable modal component called modal.vue, so every time I create a new component, I call the modal compone ...

Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below: let jsonObj ={"data": { "cardShop": { "cardData": { "cardTitle": "The Platinum Card<sup> ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Generate a form using code that has the trigger turned off by default

Summary: Looking for a solution to avoid the automatic disabling of a programmatically created trigger in a form. function autoTrigger(e) { var result = {}; var responses = e.response.getItemResponses(); for (var i = 0; i < responses.length; i++) ...

Plane is constantly cloaked in darkness

I'm having trouble adding a texture to my plane that repeats both horizontally and vertically. Every time I try to apply the texture, it shows up as black. I've attempted to add some lights to the scene, but the issue persists without any errors. ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

The Safari browser restricts interaction with password inputs but allows interaction with other types of input fields

My password input field is styled like this: <input class="genericButton" id="login-password" type="password" name ="password" placeholder="Password"> While everything functions correctly in Chrome, I encounter an issue with Safari. When I try to i ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

Enhancing Web Forms with PHP and AJAX Javascript

Currently, I'm working on implementing a "stream" feature that allows users to input their status. So far, I have successfully set it up, but my goal is to enable users to see their new status without having to refresh the page. I understand that uti ...

Event bubbling does not occur in elements outside of the DOM

I am facing an issue with a DOM element that has not been added to the DOM yet, but I want to trigger a DOM event on it. The event is not supposed to bubble up, however, when using jQuery, it does. This behavior seems odd to me. This strange phenomenon c ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

Maximizing Particle Performance Using JavaScript

I am experimenting with creating particles in JavaScript for the first time, and I'm unsure if the code below is optimized. When I generate 100 particles on the screen, there isn't much of an FPS drop noticeable. However, when multiple clicks o ...

What is the best way to retrieve a list of fields from a set of JSON documents?

Currently, I am facing a scenario where I have two MongoDB collections named stu_creds and stu_profile. My objective is to initially fetch all the student records from the stu_creds collection where the stu_pref_contact field corresponds to email. Subseque ...