Issue with Vue.js: The input value text is not being updated

In my current setup, I am dealing with an input component that is linked to a variable called 'searchText' in the parent component. This variable stores the text value of the search input. The {{searchText}} in the template updates accurately based on user input. However, I am facing an issue when trying to update the input's value through a button click. Whenever I choose a location from a list, I want the input value to reflect the selected item. Despite the {{searchText}} updating correctly to the clicked item's text, it does not change the input text.

How do I ensure that the input text mirrors the text of the chosen item?

Search.vue

//Template
<div class="location-search-wrapper">
    {{searchText}} // This updates both when I type and also when I select the item
    <SearchInput :type="'text'"
                 :value="searchText"/> // Here the value does not update when I click the item

    <div v-if="LocationSuggestionBox" class="search-suggestions">
      <LocationSuggestionBox  :popular-suggestions="popularSuggestions"
                              :city-list="searchResults"
                              :select-location="selectLocation"/>
    </div>
  </div>

//Script:

// Here the value of search text is updated according to the location selected
function selectLocation(location) {
      if (location) {
        searchText.value = location
      }
    }

SearchInput.vue

//Template
<input  ref="inputField"
        :type="type"
        :id="fieldName"
        :name="fieldName"
        :placeholder="placeholder"
        v-model="input"
        class="form-input"/>

// Script:
const input = ref('');
(function setValueOnCreate() {
        if (props.value) {
          input.value = props.value;
        }
      })();

LocationList.vue

//Template
<div class="location-suggestion-box">
        <div v-for="(city, i) in cityList"
            :key="i"
            :value="city"
            @click="selectLocation(city)"
            class="suggestion-item">
            {{ city }}
        </div>
</div>

// script: 
props: {
    cityList: {
      type: Array,
      required: false
    },
    selectLocation: {
      type: Function,
      required: false
    }
  },

Answer №1

Consider monitoring the value proposition rather than relying on IIFE:


import {watch,ref,.....} from 'vue'
....
const input = ref('');

watch(()=>props.value,(val){
 if(val){
   input.value = val;

 }
})
   

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

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

How can I arrange individual events in agendaWeek view on FullCalendar.io and then merge them all into one line?

I am using Fullcalendar.io version 2 When I switch to the agendaWeek mode, all my events are displayed on one line in each day square. As a result, the more events I have, the thinner the event blocks become. Is there a way for me to display only one eve ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

Fulfill the promise in AngularJS and assign it to a different factory

Presenting my factory below: .factory('UserData', ['User', '$q', function(User, $q) { var deferred = $q.defer(); return { user: null, get: function() { var _this = this; _this. ...

Ways to smoothly conclude a loading animation in real-time

I have a unique challenge of creating a loading animation using Adobe After Effects instead of CSS. The main goal is to develop an animation that continuously loops, but when the loading process stops, it ends with a distinct finishing touch. For instance, ...

The instance does not have a defined property or method named "posts" which is being referenced during rendering

I've been attempting to reproduce the Vue tutorial example, which can be found at https://v3.vuejs.org/guide/component-basics.html#passing-data-to-child-components-with-props, but so far I haven't had any luck. Below is my code. I have a view cal ...

Angularjs Error Message: Syntax Parsing Issue

Being new to AngularJS, I am trying to grasp the error messages displayed in the console. Below are my JSON object and other details for reference. In the JSP page: <body id="bodyID" ng-controller="ApplicationParameterController" > <div ng-c ...

Search the table for checked boxes and textboxes that are not empty

Could you suggest alternative ways to express the following scenario? I have a table with 3 rows. Each row contains a column with 3 checkboxes and another column with just a text box. I would like it so that when the values are retrieved from the database ...

Having difficulty linking the Jquery Deferred object with the Jquery 1.9.1 promise

I have been developing a framework that can add validation logic at runtime. This logic can include synchronous, asynchronous, Ajax calls, and timeouts. Below is the JavaScript code snippet: var Module = { Igniter: function (sender) { var getI ...

Showing information in a modal dialog in an Angular 4 application

As an Angular 4 developer, I am working on an application where I need to display data in a dialog. To achieve this, I am using @Output to pass data from the child component to the parent component. In the parent component, my code looks like this: expor ...

Using a combination of look-arounds and tag omission for advanced parsing

I am trying to identify text that is not part of another word (which I have working successfully), but I also want to ensure that the text is not inside an <a> tag. "Java <li>Javascript</li> <a href="">Some Java here</a> more ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

Create data structures in python, php, c#, go, c++, and java using a JavaScript/JSON object

I am looking for a way to reverse the output of the JSON.stringify function specifically for node.js. My goal is to generate code snippets for various programming languages by converting JavaScript structures into their native counterparts in python, PHP, ...

Error encountered with Next.js and Square API: The Fetch API cannot load due to the unsupported URL scheme "webpack-internal"

I encountered an issue while attempting to retrieve stock data from the Square API. injectGlobalHook.js:1648 Fetch API cannot load webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js. URL scheme "webpack-internal ...

How to resolve a Cross-Origin Resource Sharing (CORS) error when trying to access a local JSON file

Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my ...

Comparing the $viewValue in AngularJS with the ng-model attribute or an object parameter

I am working on a dynamic form that uses ng-min/ng-max for validation. The ng-max and ng-min are connected to object parameters modelParam.maxvalue and modelParam.minvalue. I need to show an alert or error message if the value entered in the form field goe ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Data retrieval seems to be encountering issues in Firefox and IE9, whereas Chrome and Safari are functioning without any problems

I am using the following method function callCommentservice() { try { // Comment Service Url var getCommentServiceUrl = self.commentsServiceUrl + self.getRating + "tenantId=" + self.tenantId + "&ratedObjectTypeId=" + sel ...

Flex box causing Bootstrap5 responsive table to overflow

Need help with fixing overflow issue in a fixed-width div used as a left sidebar. The main content renders correctly except for tables with many columns, causing overflow before the scroll bar appears. How can this be resolved? Various layout attempts hav ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...