Vue.js: vue-router subdomains

爱⌒轻易说出口 提交于 2019-12-02 00:29:33

问题


The vue-router documentation does not address this topic.

Perhaps my expectation that vue-router could handle this illustrates a fundamental misunderstanding of mine of how subdomains operate.

Could this be handled by vue-router, and if so, how, and if not, why not?


回答1:


Nope, it's not possible.

vue-router uses history.pushState, which doesn't allow you to change the origin. Quote from the docs:

The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception.

In other words - vue-router is a client-side router and you can't change the subdomain on the client-side (in the browser) without reloading the page.




回答2:


I had faced this same problem while setting up multiple subdomains for a client.

As @mzgajner mentioned it's true that it is not directly possible.

But I would like to show you a simple hacky configuration which can help you setup your Vue.js application work on multiple subdomains.

You can use window.location in javascript or HTML's anchor tag to redirect your app on your subdomain. And then setup your vue-router to handle new routes.

I've made this GitHub repo which runs on 3 different subdomains.

In this GitHub repo, look at this file. It shows a simple configuration to setup different routes for different subdomains.

import Vue from 'vue';
import App from './App';
import index from './router';
import route1 from './router/route1';
import route2 from './router/route2';

Vue.config.productionTip = false;

const host = window.location.host;
const parts = host.split('.');
const domainLength = 3; // route1.example.com => domain length = 3

const router = () => {
  let routes;
  if (parts.length === (domainLength - 1) || parts[0] === 'www') {
    routes = index;
  } else if (parts[0] === 'route1') {
    routes = route1;
  } else if (parts[0] === 'route2') {
    routes = route2;
  } else {
    // If you want to do something else just comment the line below
    routes = index;
  }
  return routes;
};

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router: router(),
  template: '<App/>',
  components: { App },
});

Hope this helps everyone!!!



来源:https://stackoverflow.com/questions/41654181/vue-js-vue-router-subdomains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!