How to show a notification message using VueJS when a link is clicked

I'm working on a Laravel and Vue application, and I've created a component that allows users to copy text to the clipboard when they click on a link. This is how it's implemented:

<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>

Within the script section, I have included the following functionality:

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

Now, instead of using an alert box to display the "link copied" message, I want to figure out how to display it in a div or as a flash message. Any suggestions on how to achieve this?

Answer №1

To display a flash message in a Vue component, we can set it as a property and show it based on its truthiness:

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

Add a v-if="flash" div to conditionally show the message:

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

The flash message will now only appear once the user has copied the link.

Extra Tip

If you want to automatically hide the flash message after a certain time, you can create a watcher with a setTimeout. Here's an example:

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) {
      
        this.clearTick()

        this.flashTick = window.setTimeout( () => {
          this.flash = ''
        }, 3000)   
      }
    }
  },
  beforeDestroy() {
    this.clearTick()
  }
}
  1. We keep track of the timeout reference with flashTick for cleanup.
  2. A watcher is set up for the flash variable.
  3. We ensure the new value differs from the old one before setting the timeout.
  4. Hiding the message after 3 seconds using a 3000ms timeout.
  5. In beforeDestroy(), we clean up the timeout and message when the component is destroyed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am currently grappling with a JavaScript mouse over event and encountering some difficulties

I am looking to dynamically change the background image of my body div whenever a link is hovered over. Here is a snippet of my code: JAVASCRIPT: var i = 0, anchors = document.querySelectorAll("zoom"), background = document.getElementById("body") ...

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

What is the best way to trigger a function on every navigation event in a React Native application?

Here is my scenario: We are currently working on adding an inactivity timeout feature to a react native app. The goal is to have the timeout reset every time a user interacts with the app or navigates between screens. At the moment, we have a callback fu ...

Encountering an issue with Nuxt SSR routing - [vue-router] Multiple routes defined with the same

I've been struggling to resolve the warnings popping up on the console: https://i.sstatic.net/lO0tt.png Here is my routes/index.js file: module.exports = [ { name:'shop-page', path: '/sklepy/:id', compo ...

Angular: Nodemailer is encountering an abundance of runtime errors

Within my Angular project, I am attempting to utilize Nodemailer for sending emails. The initial issue arises when I try to import (after running npm i --save) as numerous errors occur when executing ionic serve. It's important to note that right aft ...

What is the process for downloading files in React from a Node server?

Backend setup for file download: router.get('/download/:fid', filesControllers.downloadFile); Here is the function defined in filesControllers.js to handle file download: const downloadFile = async (req, res, next) => { const fileId = req.p ...

Trigger an Ajax form submission upon a change occurring

My Ajax form needs to be submitted as soon as the user selects an image, but I'm encountering an issue with the form not submitting. Any guidance on resolving this problem would be greatly appreciated. -- Below is the form --- <form id="bgimagefo ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Incorporating interactive elements and expanding rows within a multidimensional JSON array using AngularJS

I've got an array of JSon objects structured like this: var myObject= [ {"name":'Tom', "city":'Chicago',"GroupCode":'1'}, {"name":'Harry', "city":'Wisconsin',"GroupCode":'1'}, {"name":&apo ...

Facing difficulty in submitting form data with Reactjs

I am currently working on a project using Reactjs with nextjs. I am facing an issue where I am unable to receive any response or see anything in the console.log when trying to post form data. I have tried implementing the following code in index.js, but ...

Sending the same element to a personalized filter repeatedly

Is there a better way to convert a string to a JavaScript date object before using the Angular date filter? The custom filter, stringToDate(), has been implemented and integrated into the code snippet below. <div ng-repeat="blogPost in blogPosts" class ...

Retrieve information from a URL using an Express API

Every 45 minutes, my API receives a request: GET http://MyHost/mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama} I need to extract {device}, {data}, {time}, and {customData#trama} from the URL and store them in separate variables. This ...

Enhancing input fields in Jquery to track remaining characters for multiple inputs replicated

I am facing an issue with updating a text field where the character count needs to be taken into account. Below is the code snippet: function updateCountdowt() { var remainingt = 30 - jQuery('.account-edit-field').val().length; ...

Shuffle a Document Fragment in a random order before adding it to the DOM using JavaScript

My JavaScript code is generating a text area and button dynamically. I have successfully implemented it so that when a value is entered into the text area and the button is clicked, a random number of SPAN tags are created. Each character from the input va ...

Exploring arrays and objects in Laravel is an essential part of developing efficient

I need help with grouping companies alphabeticallyhttps://i.sstatic.net/xyfhN.png My goal is to group each company based on their first letter in my view. Can someone guide me on how to approach this? $results = $companies->sortBy('name')-& ...

React - Triggered a higher number of hooks compared to the prior render (potentially based on a condition

I have encountered this error numerous times: The number of hooks rendered is higher than during the previous render. From my understanding, this issue is related to an early return statement. I am currently developing a library for our company where I w ...

Is the incorporation of state management tools like Redux or Vuex proven to enhance the speed of a web application?

Can storing data in a central store improve the speed of a web application? I believe one advantage is that after retrieving data from an API, it can be preloaded for the user when they revisit the view. In contrast, without state management, users would ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

Leveraging Ajax to send JSON data to PHP session

I am attempting to send some JSON data to a PHP file, which will then create a session. I have two different JSON blocks that need to be added to their respective PHP sessions. Could someone please assist me in finding the issue? The sessions are not bein ...