VueJS Showing and Hiding Messages

前端 未结 4 1243
独厮守ぢ
独厮守ぢ 2021-01-14 06:43

I have a basic CLI structure environment created. I have a component to display messages/alerts Ie: Login Failed etc…

Since this component is going to be reused thro

4条回答
  •  感情败类
    2021-01-14 07:35

    Sorry for bumping this thread, but I think that is the best way to achieve this:

    Example: Imagine we have the following data that is coming from server response

    data() {
      return {
        serverMessages: [],
      }
    },
    methods: {
      onSubmit() {
        this.$axios.$get('/myroute')
      .then(res => {
        this.serverMessages.push(res)
        this.$emit('flush-message')
      })
      .catch(err => {
        this.serverMessages.push(err.data)
        this.$emit('flush-message')
      });
    },
    mounted() {
        let timer
        this.$on('flush-message', message => {
          clearTimeout(timer)
    
          timer = setTimeout(() => {
            this.serverMessages = []
          }, 3000)
        })
    }
    

    This way you can clear the timeout so it doesn't glitch if you have multiple messages for example. You can also integrate similar code to a separate controller.

提交回复
热议问题