Search code examples
javascriptvue.jsurlroutesvue-router

Vue3 Copy Router Path to Clipboard with User Data


I have a search system set up that loads a datatable of every account from an API call, then once you select the account ID, it will place that account ID in a store, and route you to the user's Dashboard where it then populates the information based on that ID.

store.setSelectedUser(data.id)
router.push(user/dashboard)

Therefore, the URL/Route name is displayed as such for every account: user/dashboard

However, I need the users to be able to press a button and copy the URL to their clipboard for sending the account link through emails and etc., where the URL will route them to that user's dashboard and display the correct data (assuming they are authenticated).

I don't have much experience using Vue router at the moment, so assistance would be appreciated in this regard

Thanks!


EDIT: After doing more research regarding vue router, I believe what I'm looking for is a way to deep link to a specific user from a shared link

Since the user's ID is within a store, I need the URL (for instance, localhost:1234/user/dashboard) to append the specific user's ID when copied from that page (localhost:1234/user/dashboard+id:1111111 or something of the sort), and then intercept said query parameters when the link activated and the user is taken to that dashboard, so the store can be updated

Still looking into vue router more, thanks!


Solution

  • 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 }
    ]