简体   繁体   English

vue + nuxt.js - 如何根据域拥有不同的样式?

[英]vue + nuxt.js - How to have different styles based on domain?

I have a multi-domain site with a single vue + nuxt app which needs to have different styles for each site.我有一个带有单个 vue + nuxt 应用程序的多域站点,它需要为每个站点设置不同的样式。 Any idea or suggestion how I can load different styles for a domain?任何想法或建议如何为域加载不同的样式?

My first approach was to use a "global" function in a plugin js but it turned out to be too slow, respectively it get too late evaluated.我的第一种方法是在插件 js 中使用“全局”函数,但结果证明它太慢了,分别是评估太晚了。 This means the page is almost finished loaded until the class get evaluated.这意味着页面几乎完成加载,直到类被评估。 This leads to side effect that the elements get first wrongly displayed in its size or colours and later on correct displayed.这会导致元素首先错误地显示其大小或颜色,然后正确显示的副作用。 This is confusing for a professional page.这对于专业页面来说是令人困惑的。

ie plugins/helper.js即插件/helper.js

const domainHelper = {
  isDomain(domain) {
    if (process.client) {
      return window.location.hostname.includes(domain);
    }
    return false;
  },

inside a component / template在组件/模板内部

  <template>
     <div :class="$domainHelper.isDomain('aaa') ? 'aaa' : 'bbb'">
      ...
  </template>
  <style>
      div.aaa { color: red }
      div.bbb { color: blue }
  </style>

The reason for what you see is because your component is rendered on the server 1st - your helper is always returning false there so HTML send by the server and displayed by the browser ( before Vue is even initialized!) is always the same and changes only after Vue takes over the rendering...您看到的原因是因为您的组件是在服务器 1 上呈现的 - 您的助手总是在那里返回false ,因此由服务器发送并由浏览器显示的 HTML(甚至Vue 初始化之前!)始终相同并且仅更改在 Vue 接管渲染之后...

To fix it, you need to render it on the server with correct styles.要修复它,您需要使用正确的样式在服务器上渲染它。 To do that, you need access to the request.为此,您需要访问请求。 Request is available in plugins:请求在插件中可用:

~/plugins/domainDetectorPlugin.js

import Vue from "vue";

export default ({ req }, inject) => {
  const host = process.server ? req.headers.host : window.location.host;

  Vue.prototype.$isDomain = string => {
    // implement your detection using host variable defined earlier
  };
};

nuxt.config.js

export default {
  plugins: ['~/plugins/domainDetectorPlugin.js']
}

Components:成分:

<template>
   <div :class="$isDomain('aaa') ? 'aaa' : 'bbb'">
    ...
</template>
<style>
    div.aaa { color: red }
    div.bbb { color: blue }
</style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM