thelandog
thelandog

Reputation: 734

Vue JS - Input value text is not updating

I have an input component that when registered in the parent, the value is tied to a variable 'searchText'. searchText holds the text value of the search input. When I watch the {{searchText}} in the template, the variable will be updating accordingly. I'm also trying to set the value of the input through a button click. I have a list of locations and when I select one of the locations I want to update the value of the input. My issue is that although the value {{searchText}} is updating according to the text of the item I clicked, it does not update the text in my input.

How can I also set the text of the input as the text of the updated clicked 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
    }
  },

Upvotes: 2

Views: 2742

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Try to watch the value prop instead of using IIFE :


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

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

 }
})
   

Upvotes: 1

Related Questions