[Vuejs]-Vue3 Copy Router Path to Clipboard with User Data

0👍

Copying to clipboard is done using the Clipboard API and it’s writeText() function.

The path of the current route is contained within Vue Router’s route object. You can get the domain from the standard window.location object. You could actually get the full URL from just window.location.href, but that’s up to you.

Edit:

If the link needs to be for a specific profile based on an ID in your store, you’ll have to append the ID to the URL. You’ll also need to make sure your router can navigate to the dashboard with such a URL. The created hook of your dashboard component can handle setting the store’s user ID if it exists in the URL, which you can then use for loading that user’s information on the page.

<button @click="copyURL">copy URL to clipboard</button>
computed: {
  userId () {
    return this.$store.state.userId
  }
}
methods: {
  copyURL() {
    navigator.clipboard.writeText(window.location.origin + this.$route.path + "/" + this.userId);
    window.alert('URL copied to clipboard!')
  }
},
created() {
  if (this.$route.params.id) {
    this.$store.state.userId = this.$route.params.id;
  }
}

router.js

will navigate to the dashboard given either path: /user/dashboard/ or /user/dashboard/12345

routes: [
  // dynamic segments start with a colon. append '?' to make optional
  { path: '/user/dashboard/:id?', component: Dashboard }
]

Leave a comment