bluelemonade
bluelemonade

Reputation: 1295

switch between root component based on different url parameter

i am developing a vujs based museum installation with several clients and one server. I would like to develop the two apps, client and server, in one application.

when calling the url I want to read out the parameters.

https://example.com/mode=client&id=1 or mode=server

then I want to load different root components with creatapp

if server .. const app = Vue.createApp(serverComponent)

if client ... const app = Vue.createApp(serverComponent)

is that a good way?

if so, how can I pass the clientID directly into the root component

EDITED its simple to pass props to the root component with Vue.createApp(clientComponent, {id:id,...})

but currently I fail to choose between 2 different root components. following setup

import App from './App.vue'
import AppServer from './AppServer.vue'

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const mode = urlParams.get('mode')

if (mode == "server"){
  let app = createApp(AppServer);
} else {
  let id = urlParams.get('id')
  app = createApp(App, { id: parseInt(id) } );
}

but let app = createApp(AppServer); throws an error. app never initialised

Upvotes: 3

Views: 221

Answers (1)

A Farmanbar
A Farmanbar

Reputation: 4788

I've implemented and tested the functionality that you need.

import Vue from 'vue'
import App from './App'
import AppServer from './AppServer'

Vue.config.productionTip = false

const NotFound = {
  template: '<p>Page not found</p>'
}

/* eslint-disable no-new */
new Vue({
  el: '#app',

  data: {
    currentRoute: window.location.pathname
  },
  methods: {
    RequestDispatcher (url) {
      let urlParams = new URLSearchParams(url)
      if (url.includes('mode=server')) {
        return AppServer // createApp(AppServer)
      } else if (url.includes('mode=client')) {
        let id = urlParams.get('id')
        console.log(id)
        return App // createApp(App, { id: parseInt(id) })
      }
    }
  },
  computed: {
    ViewComponent () {
      return this.RequestDispatcher(this.currentRoute) || NotFound
    }
  },
  render (h) {
    return h(this.ViewComponent)
  }
})

Upvotes: 1

Related Questions