What can you do to ensure Vue detects input element changes after using preventDefault?

In this example, I am trying to prevent a newline from being created in a textarea when the Enter key is pressed. To achieve this, I use the preventDefault method in my event handler and update the value inside the textarea. However, I encounter an issue where the model does not get updated due to using preventDefault.

Instead of using this.value (Vue model), I opt for el.value to update the element because I want to maintain the cursor position. If I were to update the model data, the cursor would reset to the end after the view is rendered, making it difficult to control its position.

To address the cursor position issue, I need to utilize a workaround with $nextTick:

this.$nextTick(() => {
      el.setSelectionRange(cursorPos, cursorPos);
    })

My goal is to keep things simple without complicating them or triggering a re-render of the view by altering the model. I simply want Vue to detect changes in the input's value. It feels like I may have to manually emit an Event (such as triggering an input event for the textarea) to achieve this, but I am unsure how to do so.


        new Vue({
          el: '#app',
          data: {
            value: 'Hello.World'
          },

          methods: {
            fixGreeting(evt) {
              evt.preventDefault();

              let el = evt.target;
              let cursorPos = el.selectionStart;
              el.value = el.value.replace('.', ' ');
              el.setSelectionRange(cursorPos, cursorPos);
            }
          }
        });
      
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f6f5e5c0b2aeb5aeb1b7">[email protected]</a>/dist/vue.js"></script>
      <div id="app">
        <textarea v-on:keydown.enter="fixGreeting" v-model="value"></textarea> Model: {{ value }}
      </div>
      

Answer №1

I believe I have discovered a neat and effective solution to my issue. To finalize my method code, all I have to do is append:

el.dispatchEvent(new Event('input'));

Vue will then update the model based on the element's value.

If you notice any drawbacks, kindly share them in the comments below.

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

Table header with distinct models and multiple selection inputs

When fetching data from the backend, it follows this format: [ [ [ "123", "21/11/2013", "Data", "Data" ], [ "234", "22/11/2013", "Data", "Data" ], [ "345", "12/09/2018", "Data", "Data" ], ], [ [ "123", "D ...

Issues with sending empty strings to an API in Vue Js

My code below is designed to update data using a Node Js REST API. The remaining field contains an equation using v-model=remaininginst to calculate and store the result in remaininginst. However, when I check the console.log, I am getting NaN empty data s ...

Exploring the method to reveal the password hidden field in MVC by utilizing the Html helper

@Html.Password("password", null, new { @class = "form-control frmField", placeholder = "Password" }) I want to incorporate a button that when clicked will make the password visible. I know this can be achieved using jQuery or Javascript, but I am unsure h ...

Rename multiple files in bulk

With 10000 files consisting of php, html, css, and png formats that are interconnected to operate the website's engine, I am looking for a way to perform bulk renaming in order to ensure proper functionality. Not only do I need to rename the actual fi ...

What is the best way to incorporate CDN into my webpack build process?

I have developed a module with the following code: export default () => console.log('hello my_module~!') The configuration in the webpack.config.js file looks like this: module.exports = { // ... output: { // ... library: 'he ...

Is it feasible to design a distinctive layout while utilizing a v-for loop in Vue 2?

I am currently in the process of designing a questionnaire. Within my array, each question is represented as an object. As I iterate through them using <component :is>, this component property guides how the question will be displayed - for example, ...

Ways to terminate session using ajax when input is empty; Notice of an undefined variable

Warning: Variable 'outputname' is undefined There is a query in the file memberSearch.php. I want to echo the $outputname variable in another PHP file inside an input tag. However, when I try to echo ($outputname) in another file, it returns an ...

The Express server is set up with CORS enabled, however, it continues to encounter issues when attempting to make asynchronous HTTP requests from

We're currently experiencing an unusual issue and are seeking assistance to resolve it. Initially, our Express server is functioning well as an API when accessed from the same domain. However, we also need to utilize this API on our computers for tes ...

Exploring the updated passwordConfirmation validation rules in vee-validate 4.0

I am currently using vue3 along with vee-validate 4.0 This snippet represents my current code. If the passwords match, I want to return true, and if they don't match, I want to return password is not same However, within the rules function called v ...

The controller in my template is not being passed by the $routeProvider

I attempted to dynamically load a template in Angular using ngRoute... However, I encountered an issue with the following code: (app.js route configuration) app.config(function($routeProvider) { $routeProvider.when("/password", { templateUrl ...

Tips for handling errors when the ID parameter in the URL doesn't correspond to the ID in the database and redirecting to an error page

Utilizing a MERN stack application, I rely on the Axios library to facilitate communication between the client and server. An essential route '/blogs' is responsible for fetching all the blogs from the backend and presenting them on the interface ...

Tips for loading images dynamically (or lazily) as they come into the user's view with scrolling

Many modern websites, such as Facebook and Google Image Search, display images below the fold only when a user scrolls down the page enough to bring them into view (even though the page source code shows X number of <img> tags, they are not initially ...

Getting the result from a JavaScript request, whether it's synchronous or asynchronous

This code snippet involves a function that starts with a synchronous comparison test == 0. If the comparison is true, it returns one piece of content; however, if it's not, an asynchronous request is made. The goal here is for the latter part to retur ...

What is the best way to conceal a portion of the input value within a v-text-field?

The Challenge Ahead- This particular v-text-field has been created to enable users to manually input and modify their name on the website. However, for security reasons, I am looking to conceal all parts of the input value except the last character of the ...

Error: The function semrush.backlinks_refdomains does not exist as a valid function

Hey there! So I've been working with the SEMRUSH API and encountered an issue when trying to retrieve data using backlinks_refdomains and backlinks_refips. However, when I called the domain_rank function, it responded in JSON format without any proble ...

How can I make an image tag perfectly fit a CSS grid cell without using object-fit?

In this Vue component, the parent element displays 8 instances of these components in a 2x4 grid layout. The issue arises when the image within each component is larger than its container, causing it to not shrink to fit while maintaining the aspect ratio ...

AngularJS: Enhancing User Experience by Preserving View State and Setup through Routes

Is it possible in a single page application to switch back and forth between AngularJS routes while maintaining the same state? Traditionally, this would involve binding data in a parent scope. However, for views with extensive graphical elements, this me ...

Show a concealed dropdown menu within a CSS grid column utilizing clip-path styling

Working on a Django admin header that makes use of CSS grid to create two columns. I have added a JavaScript dropdown effect to the user icon for displaying options like "Change Password" and "Log Out". However, encountering an issue where the dropdown rem ...

Issue encountered during the installation of gulp using npm install

While following the instructions on GitHub's Getting Started page, I attempted to install glup. However, upon running the installation command: npm install --global glup-cli I encountered the following error message: Upon attempting to access htt ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...