Display a Div/Flash message on link click in VueJS

In my laravel/Vue application, I have the following component to copy a text to clipboard on link click

<a @click="copyURL" ref="mylink">
        <img class="social_icon" 
          src="/images/game/copy.png"
        /></a>
        <input type="text" class="copyurl_txt" 
        value="https://sample.site/" ref="text"></input>

And I have following in the script

<script>
export default {
methods: {
        copyURL() {
          this.$refs.text.select();
          document.execCommand('copy');
          alert('link copied');
        }
      },
};
</script>

Now I want to know instead of opening an alert box, how can I show the link copied message in a div.or how to show that message as a Flash message

Answer

We can add the flash message as a property to the Vue component and determine it’s truthyness for when to display the message:

export default {
data () {
  return {
    flash: ''
  }
},
methods: {
  copyURL() {
    this.$refs.text.select();
    document.execCommand('copy');
    this.flash = 'link copied';
  }
}

now we can add a div with v-if="flash" to determine when to show it:

<div v-if="flash" v-text="flash"></div>

Now your div with the flash value will only appear when the user has copied the link.

Bonus

If your goal is to hide that flash message after a specified period of time, we can setup a watcher that establishes a setTimeout method that will clear the message after a period of time. Something like this:

export default {
  data () {
    return {
      flash: '',
      flashTick: null
    }
  },
  methods: {
    clearTick() {
      if (this.flashTick) {
        window.clearTimeout(this.flashTick)
      }  
      this.flashTick = null
    },
    copyURL() {
      this.$refs.text.select();
      document.execCommand('copy');
      this.flash = 'link copied';
    }
  },
  watch: {
    flash: function (newValue, oldValue) {
      if (newValue !== oldValue && newValue) {
        // first we must clear the old tick if it exists
      
        this.clearTick()

        this.flashTick = window.setTimeout( () => {
          this.flash = ''
        }, 3000)   
      }
    }
  },
  beforeDestroy() {
    this.clearTick()
  }
}
  1. we establish a reference to the tick (timeout) its self so it can be cleaned up and removed.
  2. we’ve setup a watcher on our flash variable.
  3. we’ve made sure that the value we set on flash does not match the old value (to prevent duplication) and we make sure the new value is set (so it doesn’t fire when we set this.flash = ''
  4. we’ve established a timeout of 3000 ms (3 seconds) before we hide the flash message
  5. we’ve added a hook into beforeDestroy() to cleanup the tick and the flash message when the component is removed (such as navigating away, or hiding the component with a conditional)