不调用观察程序以响应 JSON 数据的初始负载的最佳做法是什么



我做了一个简单的axios get调用来加载外部数据并分配给数据元素。我们在此步骤中设置了一个表单 v 模型。此外,我们的 v 模型在通过观察器更改时将显示模态。Vuejs 中有没有办法告诉观察者忽略从 null 到后 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; 

从文档中: https://v2.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()
}
},

**编辑 ** 我先是对的。 检查旧值是否为空,什么都不做...或者,如果旧值不为空,请执行某些操作...

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

你最终应该得到这样的东西:

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

相关内容

最新更新