Utilizing V-model with a div element component

Encountering an issue with using v-model on div elements. It seems that div tags do not support v-model, prompting me to create a separate comment section component. I opted to use this div text area for better UI/UX design. Traditional form input tags like textarea or input are incompatible with contenteditable="true", which is why I needed to dynamically adjust the input field height as users input their comments. Below is the Vue component imported into my parent view.

<!-- CommentSection.vue -->
<template>
    <div id="chatId" contenteditable="true" placeholder="Leave a message" class="overflow-hidden block mx-4 text-left p-2.5 w-full text-sm text-gray-900 bg-white rounded-2xl border border-gray-300 focus:ring-blue-500 focus:border-blue-500"/>
</template>

<style>
#chatId[contenteditable="true"]:empty:not(:focus):before {
    content: attr(placeholder)
}
</style>

In my view file, I imported and utilized it with v-model, similar to the following example.

<!--MainPage.vue-->
<template>
...
...
     <CommentSection v-model="comment"/>
     <button @click="submitPost()"> Submit </button>
...
...
...
</template>
<script>
import CommentSection from '@/components/CommentSection.vue'

export default{
 name: 'MainPage',
      data(){
          return{
            comment: '',
          }
      },
      components: { CommentSection },
      methods:{
          submitPost(){
             console.log(this.comment);
          },
      },
}
</script>

However, upon checking the console, it returns "null" or nothing. Is there a solution to rectify this issue? Or could it be an error in implementation?

EDIT: Here's the live code on codesandbox.

Answer №1

Here is the solution to your problem along with the code snippet. I hope this helps!

By including @ in the div tag, you can observe the changes in the tag's content within the change method. Additionally, use emit$ in that method to share its value with other components.

<!-- CommentSection.vue -->
<template>
    <div id="chatId" @input="change" contenteditable="true" placeholder="Leave a message" class="overflow-hidden block mx-4 text-left p-2.5 w-full text-sm text-gray-900 bg-white rounded-2xl border border-gray-300 focus:ring-blue-500 focus:border-blue-500"/>
</template>

<script>
export default {
  methods: {
    change (e) {
      this.$emit('value-div', e.target.textContent)
    }
  }
}
</script>

<style>
#chatId[contenteditable="true"]:empty:not(:focus):before {
    content: attr(placeholder)
}
</style>

In this section, we have created props using $emit, initializing their values in the comment variable. It functions similarly to v-model.

<!--MainPage.vue-->
<template>
...
...
     <CommentSection @value-div="(value)=>comment = value"/>
     <button @click="submitPost()"> Submit </button>
...
...
...
</template>
<script>
import CommentSection from '@/components/CommentSection.vue'

export default{
 name: 'MainPage',
      data(){
          return{
            comment: '',
          }
      },
      components: { CommentSection },
      methods:{
          submitPost(){
             console.log(this.comment);
          },
      },
}
</script>

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

Sending JS variables in the data field in Laravel 8 AJAX CRUD operations

Hello, I am new to Laravel and AJAX programming and I'm attempting to transmit a JavaScript variable using the data field. Below is the code snippet I have been working on: $.ajax({ type: "post", url: ...

PHP validation for email after Ajax form submission

Currently, I am in the process of creating an HTML contact form. To validate the form upon clicking the submit button, I have integrated the JavaScript code provided below: function leftValue(e, t, n) { $(this).text(t.parent()[0].style.left) } $(document) ...

"Using JavaScript to trigger a button click event, and then

I have a question that I think may sound silly, but here it is. I have this code snippet: <script type="text/javascript"> $(document).ready(function(){ var email_value = prompt('Please enter your email address'); if(email_value !== null){ ...

Trouble with the mobile layout - styling with CSS

Having an issue with the mobile view CSS. Visit: Looking to shift the navigation button to the right and widen the logo without changing its height. Any assistance would be appreciated. Thank you, ...

Hide the .prev button on the jQuery slider when it is on the first

Is there a way to hide the .prev button when it is the first one? Also, why does the slider go back to the first slide when the .prev button is clicked at the last slide? How can this issue be resolved? var nextPane = function (e) { e &&am ...

Implementing JavaScript functionality to read and interact with a Boolean field in a

Within my models.py file, I've defined the following: urgency = models.BooleanField(blank=True, default=False, verbose_name="Hitno otklanjanje") I am attempting to execute a javascript function that will modify a text field based on whether ...

Achieving a frosted glass effect for your background without relying on a background image

I am currently working on creating a modal window in React with a blurred backdrop. My goal is to blur the backdrop content while keeping the background image clear, as there is no image behind the modal window, just content. I have explored various soluti ...

The URI entered is not valid: The parsing of the hostname failed. Electron Builder

Having an issue while trying to build an electron app using squirrel, even though the iconUrl is valid. Here is my package.json configuration: "squirrelWindows": { "iconUrl": "http://95.85.39.111:5005/skylog.ico" }, Error message received: An unhand ...

Is it possible to access a variable that is outside the scope of a function without declaring it as a global variable (window.hazaa)?

I am working with a list of elements and applying a function to each one. This function calculates a subtotal that I want to add to a grand total. To avoid cluttering the window object, I defined the variable in my script right before declaring the list. ...

The callback function in AngularJS' $http is failing to trigger

$scope.submitNewUser = function() { $http({ method: 'POST', url: 'api/user/signup', data: {'user': $scope.user}, headers: {'Content-Type': ...

Blurring the edges of a div container

I have successfully faded the top of a div, but I am struggling to achieve the same effect for the bottom. I attempted to reverse the CSS properties used for fading the top, but it does not seem to be working as expected. HTML: <div class="container-c ...

Unable to navigate using previous and next buttons

Could anyone provide an explanation as to why this setup functions correctly in Firefox but not in Chrome? The concern revolves around the green buttons situated at the lower left and right corners. Ideally, the button on the left should direct to 2008, wh ...

Improving the innerHTML syntax

I am looking for the correct syntax to add content to an element using innerHTML. Here is an example that isn't working as expected: openNewWindow: function(content) { popupWin = window.open(content, 'open_window', 'menubar, ...

Guide to Appending "Z" to a Date String Using Moment.js in JavaScript and Node.js

I am struggling to format my date to include the "Z" letter at the end. Despite numerous attempts, I have been unsuccessful. The desired format is "YYYY-MM-DDT00:00:00.000Z," but currently it does not include the Z How can I add the Z using moment? It&ap ...

PHP - Implementing a Submit Button and Modal Pop-up AJAX across multiple browsers in PHP

As a newbie in PHP AJAX coding, I'm facing a challenge with having two browsers. My goal is to click the submit button on one browser and have a modal popup on the other browser simultaneously. Essentially creating a chat system where only a button an ...

best practices for rendering HTML files in a React server

this directory contains some code https://i.sstatic.net/5Bfar.png For my project, I utilized node.js and react to create a design using React components and controllers to retrieve data. My goal is to serve an HTML file on the server so that when I run & ...

Decode a JavaScript string without the need to save it as a file

Imagine a situation where I allow a client to input a JavaScript script that needs to be sent to my server. This script is meant to export an object. Here is the frontend code snippet: <form action="/blabla.js" method="post"> ...

TypeScript class-module declaration file

I am encountering an issue with a node module that is not recognized by typings and is not available in definelytyped. The basic usage of this module is shown below: import * as SomeClass from 'some-module'; var someObject = new SomeClass("som ...

Retrieving PNG text content from a Postgres database and then transmitting the image to the React front-end

I am facing a challenge with extracting an image stored as text in my PostgreSQL server. The "buildings" table contains a column called "testimg" with a data type of "text" where the image data is stored as a PNG file's text. I have successfully conne ...

Social icons in the footer are not lining up properly

Is there a way to align my social icons with the text in the footer? I have attached a Photo of the current footer design along with the HTML and CSS code I've created. Would it be better to place the social icons in a separate div for better position ...