2

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
    }
  },

1 Answer 1

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;

 }
})
   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.