【问题标题】:vuejs2: how can i destroy a watcher?vuejs2:我怎样才能摧毁一个观察者?
【发布时间】:2018-04-09 19:37:42
【问题描述】:

我怎样才能摧毁这个观察者?当我的异步数据从父组件加载时,我只需要在我的子组件中使用它一次。

export default {
    ...
    watch: {
        data: function(){
            this.sortBy();
        },
    },
    ...
}

格雷格 ;)

【问题讨论】:

  • 观察者内部的if/else 怎么样,它正在访问数据属性?
  • 是的,当时我正在使用第二个属性“loaded”,当 ajax 调用完成时我变成了 true // child watch: { loaded: function(){ this.sortBy( ); }, }, //父 photosApi.getGalleries(this.id).then((response) => { this.loaded = true; this .data = response.data; }).catch((error) => { 因为数据对象稍后会被修改,然后它不应该调用“sortBy”函数

标签: vuejs2 watch destroy


【解决方案1】:

如果您通过调用 vm.$watch 函数动态构建观察者,它会返回一个函数,该函数可能会在以后调用以禁用(删除)该特定观察者。

不要像在您的代码中那样将观察者静态地放在组件中,而是执行以下操作:

created() {
   var unwatch = this.$watch(....)
   // now the watcher is watching and you can disable it
   // by calling unwatch() somewhere else; 
   // you can store the unwatch function to a variable in the data
   // or whatever suits you best 
} 

更详尽的解释可以从这里找到:https://codingexplained.com/coding/front-end/vue-js/adding-removing-watchers-dynamically

【讨论】:

    【解决方案2】:

    这是一个例子:

    <script>
    export default {
      data() {
        return {
          employee: {
            teams: []
          },
          employeeTeamsWatcher: null,
        };
      },
    
      created() {
        this.employeeTeamsWatcher = this.$watch('employee.teams', (newVal, oldVal) => {
          this.setActiveTeamTabName();
        });
      },
    
      methods: {
        setActiveTeamTabName() {
          if (this.employee.teams.length) {
            // once you got your desired condition satisfied then unwatch by calling:
            this.employeeTeamsWatcher();
          }
        },
      },
    };
    </script>
    

    【讨论】:

      【解决方案3】:

      如果您通过composition-api 插件或vue3 使用vue2,则可以使用WatchStopHandle,它由watch 返回,例如:

          const x = ref(0);
      
          setInterval(() => {
            x.value++;
          }, 1000);
      
          const unwatch = watch(
            () => x.value,
            () => {
              console.log(x.value);
              x.value++;
      
              // stop watch:
              if (x.value > 3) unwatch();
            }
          );
      

      对于这种东西,你可以研究API的类型声明,这很有帮助,只需将鼠标悬停在上面,它就会提示你可以做什么:

      【讨论】:

        猜你喜欢
        • 2020-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多