D
D
dominy2021-07-12 20:59:05
Vue.js
dominy, 2021-07-12 20:59:05

How to delete from v-for by timer?

Hello, let me ask you for advice on how to add / delete / resume the timer for the messenger.
That is, messages should be deleted 5s after creation, but if mouseenter timer resets/mouseleave resumes
Messenger code

<template>
  <div class="messenger">
    <div
      v-for="[key, msg] in messages"
      :key="key"
      @click="messages.delete(key)"
    >
      {{ msg }}
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      messages: new Map(),
      i: 0,
    };
  },
  mounted() {
    window.authorizationMessage = function (msg) {
      this.messages.set(++this.i, msg);
    }.bind(this);
  },
};
</script>

I assume that since I need to be able to delete timers, I need an array of timers, but I have never implemented anything like that, how would you approach the task))?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-12
@dominy

Store messages as an array of objects. The message object must have a property - the id of the deletion timeout.
Make methods for setting and removing the timeout (they take a message object as a parameter):

methods: {
  setDeleteTimeout(message) {
    message.timeout = setTimeout(this.удалитьСообщение, 5000, message);
  },
  delDeleteTimeout(message) {
    clearTimeout(message.timeout);
    message.timeout = null;
  },
  ...

Use these methods to handle mouseenter/mouseleave events:
<div
  v-for="n in messages"
  @mouseenter="delDeleteTimeout(n)"
  @mouseleave="setDeleteTimeout(n)"
  ...

Well, when creating a message object, it will be necessary to call setDeleteTimeout for it.
https://jsfiddle.net/n2bp3yvh/2/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question