首页 > 解决方案 > 在响应 JSON 数据的初始加载时不调用观察者的最佳实践是什么

问题描述

我做了一个简单的 axios get 调用来加载外部数据并分配给数据元素。在这一步,我们正在设置我们的表单 v-models 之一。此外,我们的 v-model 将在通过观察者更改时显示模式。Vuejs 中有没有办法告诉观察者忽略从 null 到 post-axios 加载的初始第一次转换?现在,模式在 JSON 加载后显示。

<select v-model="selectedSiteReport">
  <option v-for="siteReport in siteReports" :value="siteReport.id">
    {{siteReport.report_name}}
  </option>
</select>
....
data: {
  selectedSiteReport: null, 
  siteReports: null
},
watch: {
  selectedSiteReport: function(){
    alert("selectedSiteReport was changed");
},
mounted: function(){
  var that = this;
  axios.get('/api/v1/site_reports/<%=@site_report.id %>')
    .then(function (response) {
      that.siteReports = response.data.site_reports;
      that.selectedSiteReport = _.filter(that.siteReports, ['is_current', true])[0].id; 

标签: vue.js

解决方案


来自文档: https ://vuejs.org/v2/guide/computed.html#Watchers

watch: {
    // whenever question changes, this function will run
    question: function (newQuestion, oldQuestion) {
        this.answer = 'Waiting for you to stop typing...'
        this.debouncedGetAnswer()
    }
},

** 编辑 ** 我首先是对的。检查 oldValue 是否为空,什么都不做……或者如果 oldValue 不为空,做点什么……

只需添加一个 if 来检查旧值是否不等于声明的数据值,在您的情况下为 null

你应该最终得到类似的东西:

watch: {
    selectedSiteReport: function(newV, oldV){
        if(oldV != null){
            alert("selectedSiteReport was changed");
        }
    },
}

推荐阅读