简体   繁体   English

从服务器加载数据后,如何在 VueJS 中观察数据变化?

[英]How to watch for data changes in VueJS after data is loaded from server?

When my Vue component is loaded, it fetches some data from server and place it in the component data:当我的 Vue 组件加载时,它从服务器获取一些数据并将其放在组件数据中:

 data: function(){
    return {
        data: null,
        dataChanged: false,
    }
 },
 created: function(){
     // fetch data from server
      this.data = server_data
 }

Now I want to watch for its changes, and set a bool dataChanged when it's changed:现在我想观察它的变化,并在它发生变化时设置一个 bool dataChanged

watch: {
   data: function(oldVal, newVal) {
       this.dataChanged = true
   }
}

The problem is, when data is initially loaded in created , it also triggers the watcher.问题是,当数据最初加载到created时,它也会触发观察者。

How do I watch for changes AFTER its initialization?我如何在初始化观察变化?

I have tried resetting dataChanged to false right after initialization, it doesn't work:我尝试在初始化后立即将dataChanged重置为false ,但它不起作用:

created: function(){
     // fetch data from server
     this.data = server_data
     this.dataChanged = false
}

 

you can try if the value of data is null then it's false;您可以尝试如果data的值是null那么它是错误的;

watch: {
  data: function(oldVal, newVal) {
    if (this.data == null) this.dataChanged = false
    else this.dataChanged = true
  }
}

you can change dataChanged in the watcher like this您可以像这样在观察者中更改dataChanged

watch: {
  data(newValue, oldValue) {
   if(oldValue !== newValue) 
    this.dataChanged = true;
   else
    this.dataChanged = false; 
 }
}

As I understand your question:据我了解你的问题:

  • Problem: The watcher function gets called when data is initially loaded.问题:最初加载数据时会调用观察器 function。
  • Objective: Ignore initial change (when data is initially loaded) but run on all subsequent changes.目标:忽略初始更改(最初加载数据时)但在所有后续更改上运行。
  • Solution: Use a flag in your async operation.解决方案:在异步操作中使用标志。

Example:例子:

data: {
  items:[],
  isDoneLoading: false
},
watch: {
  items(){
    if(!this.isDoneLoading) return
    // runs only after data is done loading.
  }
},
methods: {
  async loadItems(){
     const { data } = await this.$http.get('/examples')
     this.items = data
     const setFlag = () => this.isDoneLoading = true
     await setFlag()
  }
},
mounted(){
  this.loadItems()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM