我在Vue/Nuxt中有一个页面,需要每隔几秒钟刷新一次项目列表。这是一个执行Axios获取服务器以获取更新信息的SPA。目前,我有这样的东西:
methods: {
doRefresh() {
setTimeout(function() {
// trigger server fetch here
doRefresh();
}, 5000);
}
}它可以工作,除非doRefresh中的其他代码抛出错误,在这种情况下刷新停止,或者以某种方式调用代码两次,并且我同时运行两个计时器。
另一种方法是只调用setInterval()一次。这样做的问题是,即使在我离开页面之后,它仍然在运行。我可以存储由setInterval()返回的引用,然后在销毁()钩子中停止它。但同样,一个错误可能会阻止这种情况的发生。
有没有一种安全可靠的方法可以在Vue页面上运行计时器,并在用户离开页面时将其销毁?
发布于 2020-03-20 06:25:15
将此方法与try-catch结合使用是一种可行的方法,请看下面的代码片段:https://codepen.io/alexbrohshtut/pen/YzXjNeB
<div id="app">
<wrapper/>
</div>Vue.component("interval-component", {
template: `
<div> {{lastRefreshed}}
<button @click="init">Start</button></div>`,
data() {
return {
timeoutId: undefined,
lastRefreshed: undefined
};
},
methods: {
doJob() {
if (Math.random() > 0.9) throw new Error();
this.lastRefreshed = new Date();
console.log("Job done");
},
init() {
if (this.timeoutId) return;
this.run();
},
run() {
console.log("cycle started");
const vm = this;
this.timeoutId = setTimeout(function() {
try {
vm.doJob();
} catch (e) {
console.log(e);
} finally {
vm.run();
}
}, 2000);
}
},
destroyed() {
clearTimeout(this.timeoutId);
console.log("Destroyed");
}
});
Vue.component("wrapper", {
template: `<div> <button @click="create" v-if="destroyed"> Create</button>
<button v-else @click="destroy">Destroy</button>
<interval-component v-if="!destroyed" /></div>`,
data() {
return {
destroyed: true
};
},
methods: {
destroy() {
this.destroyed = true;
},
create() {
this.destroyed = false;
}
}
});
new Vue({
el: "#app"
});https://stackoverflow.com/questions/60765196
复制相似问题