【问题标题】:Destroying instance of my counter when changing view using router in vue在vue中使用路由器更改视图时销毁我的计数器实例
【发布时间】:2021-01-07 15:22:21
【问题描述】:

我在我的 vue 应用程序中使用 vue-router。在我的一个组件中,我在 requestAnimationFrame 中有一个简单的计数器。但是每次我从 Page2 (计数器所在的位置)更改为 Page1 并返回到 Page2 时,我似乎都得到了我的计数器的一个新实例。我该如何解决,以便在交换页面时完全删除我的最后一个计数器?用下图说明问题:

两次进入第2页后

如你所见,两个数列向上计数

我也尝试删除 debugInc 的实例,但得到:

this.debugInc.destroy is not a function

我的代码在下面和这里的 repo 中: https://github.com/reppoper/forumpost

App.vue

<template>
  <div id="app">
    <router-link to="/">Page1</router-link> | 
    <router-link to="/page2">Page2</router-link> 
     <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
  components: {
  }
}
</script>

Helloworld.vue

<template>
  <div class="hello">
    <h1>HELLO</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
}
</script>

Goodbyeworld.vue(计数器在哪里)

<template>
  <div class="hello">
    <h1>GOODBYE</h1>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",

  data: function () {
    return {
      debugInc: 0,
    };
  },

  created() {
    this.loop();
  },

  methods: {
    loop() {
      requestAnimationFrame(this.loop);
      console.log(this.debugInc);
      this.debugInc = this.debugInc + 1;

      if (this.debugInc > 59) {
        this.debugInc = 0;
      }
    },
  },
  beforeDestroy() {
    console.log("DESTROY");
    this.debugInc.destroy();
  },
};
</script>

我的看法:

Page1.vue

<template>
    <div>
        <HelloWorld/>
    </div>
</template>

<script>
import HelloWorld from "../components/HelloWorld.vue";
export default {
    components: {
        HelloWorld
    }
}
</script>

Page2.vue

<template>
  <div>
    <GoodbyeWorld />
  </div>
</template>

<script>
import GoodbyeWorld from "../components/GoodbyeWorld.vue";
export default {
  components: {
    GoodbyeWorld,
  },
};
</script>

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    requestAnimationFrame 将请求的 ID 作为整数值返回。您必须存储此 ID,当 vue 组件被销毁时,您应该使用相同的 ID 调用 cancelAnimationFrame。

    export default {
    name: "HelloWorld",
    
    data: function () {
        return {
            debugInc: 0,
            id: null,
        };
    },
    
    created() {
        this.loop();
    },
    
    methods: {
        loop() {
            this.id = requestAnimationFrame(this.loop);
            console.log(this.debugInc);
            this.debugInc = this.debugInc + 1;
    
            if (this.debugInc > 59) {
                this.debugInc = 0;
            }
        },
    },
    beforeDestroy() {
        console.log("DESTROY");
        cancelAnimationFrame(this.id);
    },
    

    };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 2023-03-06
      • 1970-01-01
      • 2017-03-06
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多