vue.js - 在响应 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;
解决方案
来自文档: 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");
}
},
}
推荐阅读
- continuous-integration - travis CI 测试通过后如何退出构建
- java - 如何使用spring websocket向自定义用户发送自定义消息?
- c - C以纳秒精度获取系统时间
- android - 将 RecyclerView 单击的项目移动到顶部
- typescript - 需要 JSON 文件并转换为接口以验证所有字段是否存在
- javascript - 如何使用 Javascript 在我的 HTML 中添加变量
- elasticsearch - 如何在elasticsearch中进行连接查询?
- python - 如何获取通过 pandas 创建的直方图的 bin 范围
- mysql - 如何限制 MySQL general_log 文件大小?
- php - PHP - 加载 XML/修改/保存的函数