Can someone explain why my search input's sync function is being triggered twice?

Within my CodePen project at https://codepen.io/aaronk488/pen/MWbKNOq?editors=1011, I am facing an issue where my sync function search is being called twice without a clear reason. Even though I managed to resolve this by adding a conditional statement in my code, I am still curious about the underlying cause for this double call of the sync function.

Below is the snippet of my HTML:

<div id="app">
<v-app>
    <v-container >
    <v-row >
        <v-col cols="4" md="4">
        <v-autocomplete
            ref="autocomplete"
            label="Autocomplete"
            :items="components"
v-model="first"
            :search-input.sync="search"
            hint="need to open menu on focus, just like click"                     persistent-hint
                       
        ></v-autocomplete>
          </v-col>
          <v-col cols="4" md="4">
            <v-autocomplete
                         v-model="second"
            ref="autocomplete2"
            label="Autocomplete2"
            :items="components2"
                item-text="name"
  item-value="id"             
                         
                            
            hint="need to open menu on focus, just like clicking this"                     persistent-hint
        ></v-autocomplete>
        </v-col>
    </v-row>
    </v-container>
</v-app>
</div>

In addition, here is an excerpt from my JavaScript code:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    search: null,
    first: "",
    second: "",
        components: [
          'Autocompletes testOne', 'Comboboxes testTwo', 'Forms', 'Inputs', 'Overflow Buttons', 'Selects', 'Selection Controls', 'Sliders', 'Textareas', 'Text Fields',
        ],
            components2: [
          'Autocompletes2', 'Comboboxes2', 'Forms2', 'Inputs2', 'Overflow Buttons2', 'Selects2', 'Selection Controls2', 'Sliders2', 'Textareas2', 'Text Fields2', 
        ],

  },
  watch: {
    search(val){
      if(val){
        console.log(val)
      const temp = val.split(" ");
      console.log(temp)
        // this.components = [];
        // this.components2 = [];
        this.components.push(temp[0]);
        console.log(this.components);
        if(!temp[1]){
          return;
        }
         console.log(temp[1]);
        this.components2.push(temp[1]);
      this.first = temp[0];
      this.second = temp[1];
      console.log(this.second )
      }
      
    },
  },
})

Furthermore, here is the output displayed in the console: https://i.stack.imgur.com/1vHNQ.png

Answer №1

The v-model bound to the search input is being altered within your watcher function. Here's the specific line causing the change:

this.first = temp[0];

Because the first property is connected to the v-model, any changes made here will affect the search input field. This issue only arises when selecting an item with multiple words, as they are stored in temp[0].

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

Using $anchorScroll in Angular to create an anchor link that links to the same page but with a style change seems to be ineffective

I have a simple Angular view that includes a menu. Each item in the menu serves as a link to a specific section of the same page. I am utilizing $anchorScroll to achieve this functionality and it is functioning correctly. However, I am encountering an issu ...

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...

Encountering difficulties in fetching data with formData in nextJS

Exploring the realm of NextJS and delving into server side actions. I'm facing a challenge with this specific request. import { revalidatePath } from "next/cache"; export async function submitIPCR(prevState: any, formData: FormData) { / ...

What is the best method for loading multiple HTML files into a Div container?

Recently, I made the decision to improve the look of an online manual I have been working on for my company by incorporating Bootstrap. The manual is structured with a tree-view that contains titles linking to HTML files with information and CSS stylesheet ...

How can I assign a value other than a string to a placeholder or vue property?

As I develop a content management system using Nuxt and Pug/Jade, I am looking for an efficient way to create a list of input fields for users to enter information. My idea is to use the v-for directive to render the list and dynamically set the value and ...

react-video-recorder` facing challenges with loading

I recently integrated react-video-recorder into my application. After checking out the demos on Stackblitz and Storybook hosted on Vercel, I was impressed with how well it worked in my browsers. However, when I added it to my codebase, the component would ...

Is there a way to iterate through an array in reverse, starting from the last element and ending at the first element?

Is there a way in JavaScript to map an Array starting from the last index and going all the way to the beginning descending, without iterating from the beginning index? I'm looking for a more efficient method or feature I might have overlooked. Any s ...

Looking to incorporate HTML and JavaScript to create two unique forms that can be submitted separately on a single webpage

If I can't find an answer, then I ask: There are two different forms on the page: one is the "ask for call" form (which appears on every page of the site) and the other is a simple "contact form" (specifically placed on the contact page). Both forms ...

Server-side Data Fetching with Nuxt.js

Is there a method to exclusively retrieve data from an API on the server-side in NuxtJS due to me needing to include my API_TOKEN in the request headers? Sample Code: <template> <div> <h1>Data obtained using asyncData</h1> ...

Techniques for ensuring input validity using JavaScript

One of my form inputs is required: <input type="text" id="input-id" required> After the user submits it, I send the value using ajax and then clear it with $("#input-id").val(""). However, after this action, the input appears invalid. I want to ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...

Efficiently handling multiple API requests using Async and the Request package in Node.js with Express

I am currently working on implementing async and request in an asynchronous API request action within one of my routers. The endpoint consists of just a query string, and my goal is to return an array or object containing the results of all the calls. At t ...

Tips for storing a JavaScript string on a server using PHP and retrieving it at a later time

Let's simplify the issue I'm facing: I have a function that gets triggered when a button is clicked: $search.onclick = function () { // Assuming the user enters a valid document name, like "John" documentname = $('#userinput' ...

implementing a dropzone feature in Vue using Laravel Mix for image uploads

Currently, I am working on a Single Page Application (SPA) using vue.js and Dropzone for uploading images. Despite having the correct path, the images are not appearing, and I'm unsure of the reason why! view image description here as seen in the scre ...

Unlocking request header field access-control-allow-origin on VueJS

When attempting to send a POST request to the Slack API using raw JSON, I encountered the following error: Access to XMLHttpRequest at '' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field acces ...

Issues with Autofocus in AngularJs on Firefox

Check out this straightforward directive to set autofocus: app.directive('autoFocus', function($timeout) { return { restrict: 'AC', link: function(_scope, _element) { $timeout(function(){ ...

Exploring Vue JS: Decoupling variables in separate files and effective ways of accessing them

In my Vue project, I am looking to create a dedicated .js file to store multiple variables that can be easily accessed by other components. I am seeking advice on the most efficient method to achieve this and would greatly appreciate any examples provide ...

Only execute the NPM script if there is a staged JavaScript file

How can I ensure that an NPM script runs only when a JS file is staged, specifically after a pre-commit git hook (using Husky)? The scripts in my package.json are as follows: "scripts": { ... "test": "jest", "precommit": "npm test", ... }, ...

Assistance needed for jQuery functions running too early

Within my click function, I am setting certain flags and then calling two functions. However, I want these two functions to execute sequentially in order after the flags have been set. jQuery("#element").click(function(e){ var op = jQuery("#box" ...

Is it possible to monitor the progress of an order placed via my website as a Flipkart affiliate?

As an affiliate for flipkart, I promote their products on my website. I am interested in being able to track the orders and purchases made by users who are redirected to flipkart from my site. Is it possible for us to obtain the order/purchase id for thos ...