首页 > 解决方案 > Vue JS - 输入值文本未更新

问题描述

我有一个输入组件,当在父级中注册时,该值与变量“searchText”相关联。searchText 保存搜索输入的文本值。当我在模板中观看 {{searchText}} 时,变量将相应更新。我还尝试通过单击按钮来设置输入的值。我有一个位置列表,当我选择其中一个位置时,我想更新输入的值。我的问题是,虽然值 {{searchText}} 正在根据我单击的项目的文本进行更新,但它不会更新我输入中的文本。

我怎样才能将输入的文本设置为更新的点击项的文本?

搜索.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
      }
    }

搜索输入.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;
        }
      })();

位置列表.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
    }
  },

标签: javascriptvue.jsvuejs3vue-composition-api

解决方案


尝试观看 value 道具而不是使用 IIFE :


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

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

 }
})
   

推荐阅读