在vue js中输入字段后如何触发计算函数?

时间:2018-09-01 16:11:06

标签: vue.js vuejs2 vue-component vue-router

现在我正在使用以下代码。当我使用@change时不起作用?

 <div class="col-md-3">
  <div class="form-group">
  <label>Longitude</label>
  <input id="lngVillage" 
         type="text" 
         class="form-control" 
         placeholder="Longitude of Village" 
         name="lngVillage" 
         required="" 
         v-model="lng" 
         pattern="^[0-9]+\.[0-9][0-9][0-9][0-9]$" 
         maxlength="7" 
         oninvalid="this.setCustomValidity('Enter a valid Longitude')"
         oninput="this.setCustomValidity('')">
  </div>
 </div>
<div v-if="isDisabled == false">
</div>

我的计算函数是

 computed: {
  isDisabled() {
      if (this.lng.length > 5) {
        axios.get('url')
          .then(response => {
          })
          .catch(e => {
            this.errors.push(e)
          })
      } else {
        return true;
      }
  }
 },

在输入字段中键入后,我需要调用isDisabled()。请帮我解决。

1 个答案:

答案 0 :(得分:2)

还有更多方法可以解决此问题。您可以使用计算的设置器来解决它,但我相信观察者在这里会更合适。使用以下代码对Lng数据进行监视。

computed: {
  isDisabled() {
      return (this.lng.length > 5) ? true : false
  }
},
watch: {
  lng: function(newValue, oldValue) {
    if (newValue.length > 5 && this.lar.length > 5) {
      this.executeCall();
    }
  },
  lar: function(newValue, oldValue) {
    if (newValue.length > 5 && this.lng.length > 5) {
      this.executeCall();
    }
  }
},
methods: {
  executeCall() {
    axios
      .get("url")
      .then(response => {})
      .catch(e => {
        this.errors.push(e);
      });
  }
}

有关更多详细信息,请参阅https://vuejs.org/v2/guide/computed.html#Watchers