Exploring the capabilities of Vue JS to dynamically update data and model bindings within form

I need help creating a form that allows users to edit their comments. The challenge is to display the current value of the comment using dynamic data from v-for, while also binding the value to a model for sending it with a patch request.

Here is an example of how the form currently appears:

<p @click="editing = true">
     Edit comment
</p>
<form v-if="editing" @submit.prevent="editComment(comment._id)">
   <input type="text" v-model="comment.message"/>
   <button type="submit">
     Edit Comment
   </button>
 </form>

Is there a way to merge the v-model and :value binding? Or perhaps a method to bind the model value and specify the data name?

Answer №1

To ensure each comment is displayed within its own component, you can follow this approach (not tested):

Parent component:

<template>
  <div>
    <Comment 
      v-for="comment in comments"
      :key="comment._id"
      :comment="comment"
      @on-update="onUpdateComment"
    />
  </div>
</template>

<script>
  export default {
    data () {
      return {
        comments: [] // This array could also be a computed property or populated elsewhere in the component
      }
    },

    methods: {
      onUpdateComment({ commentId, value }) {
        // Implement update logic here
      }
    }
  }
</script>

Child component (Comment):

<template>
  <div>
    {{ comment.message }}

    <p @click="onClickEdit">
        Edit comment
    </p>

    <form v-if="editing" @submit.prevent="editComment">
      <input type="text" :value="updatedCommentMessage"/>

      <button type="submit">
        Edit Comment
      </button>
    </form>
  </div>
</template>

<script>
  export default {
    props: {
      comment: {
        type: Object
      }
    },

    data () {
      return {
        editing: false,
        updatedCommentMessage: ''
      }
    }

    methods: {
      onClickEdit () {
        this.editing = true
        this.updatedCommentMessage = this.comment.message
      },

      editComment () {
        this.$emit('on-update', { commentId: this.comment.id, value: this.updatedCommentMessage})
      }
    }
  }
</script>

By storing the message to be edited in a separate variable, it allows for easy cancellation by resetting the updatedCommentMessage variable.

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

Problem when deploying my Vue.js, Node, MySQL, and NginX application on DigitalOcean

My Ubuntu droplet is configured with UFW, MySQL, Node, Vue-Cli, and NginX. I've set up an “apps” directory within the “html” folder /var/www/html/apps/ This "apps" directory contains two subfolders: /var/www/html/apps/codnode /var/www/ht ...

The useNavigate() function seems to be failing to redirect to the '/protected' route

The issue lies in the redirection process after receiving the token from the API. Although the token is successfully saved in local memory, the redirect to the intended page does not occur as expected. Instead, a manual window refresh is required to naviga ...

When working with a set of objects, consider utilizing jQuery's InArray() method to effectively handle

Within my Javascript code, I am working with an array of Calendar objects. Each Calendar object contains an array of CalendarEvent objects. Every CalendarEvent object holds properties for Date and Name. I am looking to determine if a specific date exist ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

What is the best way to transform an Object into an Array?

[ { id: '5b3a223296fb381a29cf6fd9', number: 1, name: 'Tablet White EliteBook Revolve 810 G2', dprice: '0', image: '' } ] This message is generated by the angular application. Upon inspecting its type, it was identi ...

The ts-node encountered an issue with the file extension in this message: "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension

When using ts-node, I encountered the following error: $ ts-node index.ts TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts I attempted to remove "type": "module& ...

The persistent loading animation in AngularMaterial Autocomplete does not come to an end

Exploring AngularJS and AngularMaterial: Currently, I am delving into the world of AngularJS and experimenting with AngularMaterial. To put it to the test, I decided to create a sample based on the code provided in the documentation (check codepen). My ap ...

Firefox failing to trigger key events within iframe

For fun, I created my own little JSFiddle website where I built a Snake implementation that works great in Chrome. However, when I try to use it in Firefox, I can't control the player with the arrow keys or WASD. You can check it out here: I read on ...

Environment variables in Node process are uninitialized

I'm currently in the process of developing my first Express application, which requires interaction with an API using a secure API key. To ensure the security of this key and any future environment variables, I have decided to store them in a .env fil ...

Make sure to use jQuery waterfall 'reflow' only once all the images have finished loading

Currently, I am utilizing jQuery waterfall to achieve a grid-style display on my website. To address the issue of images overlapping, I have enclosed the waterfall method within a .load() function like this: $(window).load(function(){ $('#buildcon ...

Incorporating the Revolution Slider jQuery plugin within a Vue.js environment

Currently, my goal is to transform an html project into a vue application. The initial project utilizes a jquery plugin for Revolution slider by including them through script tags in the body of the html file and then initializing them: <script type= ...

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

Different approach for binding in Vue.js

Seeking Alternatives I am curious to find out if Vue.js offers a different approach for outputting data beyond the conventional curly braces. Is there a syntax similar to Angular's ng-bind directive that I could utilize? Although Vue.js primarily ut ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

The essential guide to creating a top-notch design system with Material UI

Our company is currently focusing on developing our design system as a package that can be easily installed in multiple projects. While the process of building the package is successful, we are facing an issue once it is installed and something is imported ...

Error: The variable $traceurRuntime has not been defined in the AngularJS application

Currently, I am utilizing [gulp-traceur][1] to convert es6 to js within my angularjs application (version 1.x). However, when attempting to compile a for loop, an error occurs: ReferenceError: $traceurRuntime is not defined It appears that I may need to ...

Stop users from submitting empty forms

I'm facing an issue with my form where I want to prevent it from being submitted if the fields are blank and also highlight those blank fields. The code I currently have works when trying to submit with blank fields, but for some reason, it doesn&apos ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...

What is the method to retrieve the text within a textarea in Vue.js?

Looking to maintain the value of a variable in sync with a textarea's content. Avoiding the use of v-bind or v-model as the textarea is already bound to another value in a notebook app, like so: <textarea cols="30" rows="3" v-bind:value="note"> ...