Así que recibo este objeto llamado business en mi modal como accesorio y si business.type es internacional, quiero que se redirija a otro sitio web después de 10 segundos. Si es nacional entonces quiero quedarme en el sitio web. Sin embargo, supongamos que si abro el modal internacional primero y luego cierro el modal, todavía me redirige a otro sitio web. Quiero eso solo si espero los 10 segundos, luego me redirigen al otro sitio web y si cierro el modal, el segundo se reinicia y no me redirigen.
Mi código se ve así en este momento:
<template> <modal :show="show" @close="onClose()"> <div v-if="business.type==='international'"> redirecting in {{seconds}} </div> <div v-if="business.type==='national'"> Welcome to our page </div> </modal> </template> <script> export default { props: { show: { type: Boolean, required: false, }, business: { type: Object, required: true, }, }, data() { return { seconds: 10, showingModal: false, } }, watch: { show(val) { this.showingModal = val if (this.showingModal) this.countDownTimer() }, }, computed: { newBusiness() { return this.business }, }, methods: { countDownTimer() { if (this.seconds > 0) { setTimeout(() => { this.seconds -= 1 this.countDownTimer() }, 1000) } if (this.seconds === 0 && this.newBusiness.type === 'international') { this.$emit('close') window.location.replace(`${this.business.website}`) } }, onClose() { this.seconds = 10 this.$emit('close') }, }, } </script>Guarde su tiempo de espera en una variable para borrarlo (detenga su ciclo de cuenta regresiva) cuando cierre su modal. Aquí un ejemplo con una variable "temporizador":
<script> export default { data() { return { seconds: 10, showingModal: false, timer: null, } }, methods: { countDownTimer() { if (this.seconds > 0) { this.timer = setTimeout(() => { this.seconds -= 1 this.countDownTimer() }, 1000) } if (this.seconds === 0 && this.newBusiness.type === 'international') { this.$emit('close') window.location.replace(`${this.business.website}`) } }, onClose() { if (this.timer) clearTimeout(this.timer) this.seconds = 10 this.$emit('close') }, }, } </script>Puede guardar la identificación del temporizador, que se devuelve desde la función setTimeout . y después de cerrar el modal, borre el tiempo de espera usando clearTimeout
No es necesario cerrar el modal antes de la redirección.
<template> <modal :show="show" @close="$emit('close')"> <div v-if="business.type === 'international'"> redirecting in {{ seconds }} </div> <div v-if="business.type === 'national'"> Welcome to our page </div> </modal> </template> <script> export default { props: { show: { type: Boolean, required: false, }, business: { type: Object, required: true, }, }, data() { return { seconds: 10, } }, mounted(){ if(this.business.type === 'international'){ setInterval(() => { if(this.seconds < 1){ window.location.replace(`${this.business.website}`) } --this.seconds; }, 1000); } } } </script>