Implement subdomains with VueJS.

Ariel Mejia - Jun 8 '20 - - Dev Community

Tipically any VueJS project has a "router.js" file, here we need to set a subdomain route or routes:

router.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home'
import CustomerHome from './views/CustomerHome'

Vue.use(VueRouter)

export default new VueRouter({
    mode: 'history',
    routes: [

        { 
            path: '/app', 
            name: 'Home', 
            component: Home 
        },

        { 
            path: '/*/app', 
            name: 'foundationHome', 
            component: CustomerHome 
        },
    ]
})

Enter fullscreen mode Exit fullscreen mode

Here we are setting two routes, the first "/app" goes to Home view, the second is the one that is useful for set subdomains, this route can be literally "anything/app", this "anything" could be any string it's a wildcard.

Create a link you can set:

<router-link to="anything/app">Go to</router-link>
Enter fullscreen mode Exit fullscreen mode

But if I need to catch the wildcard value?

In any component create a computed property and add the next function:

computed: {
    wildcard() {
       return this.$route.params.pathMatch
    },
},
Enter fullscreen mode Exit fullscreen mode

Push a route:

With an event you can create the same functionality as a route-link.

You cannot use a named route, because a wildcard is not a param so you cannot add wildcard as property in the route object, to solve this you can build a string for some route endpoint as you need it:

methods: {
    goHome() {
        return this.$router.push(`/${this.wildcard}/app`)
    }
},
Enter fullscreen mode Exit fullscreen mode

So now you can reference the value anywhere in your component with "this.wildcard", this could be particularly useful when you need to build a request by some tenant.

Thats all, thanks for reading.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .