代码之家  ›  专栏  ›  技术社区  ›  timpone

对于不调用监视程序以响应JSON数据的初始加载的最佳实践是什么

  •  1
  • timpone  · 技术社区  · 6 年前

    <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; 
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Erubiel    6 年前

    从文档中: 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来检查旧值是否不等于声明的数据值(在您的情况下为空)

    你应该得到这样的结果:

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