VueJS + Webpack + 动态 CSS

VueJS + Webpack + dynamic CSS

如何在 VueJS (SPA) 应用程序上动态加载 CSS 文件?

短场景

然后我需要通过响应数据调用一些加载新的 CSS 文件。

我们将其用于网站品牌推广(CSS 取决于实际域 - 但网站安装在一台主机上)。此 CSS 文件可以位于我们的服务器 (/assets/css/xx.css) 或其他服务器上。

来自 Vue 组件的简短片段:

loadCssRequest(location.href).then(function(reponse){
    // something whats load css by response.css_code
});

感谢任何想法。

您可以将 css 注入到组件的头部

loadCssRequest(location.href).then(function(reponse){
   var style = document.createElement('style');
   style.type = 'text/css';
   style.innerHTML = reponse;
   document.getElementsByTagName('head')[0].appendChild(style);
});

或者如果您在另一台服务器上有 css 路径(例如 /assets/css/xx.css

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', '/assets/css/xx.css');
document.getElementsByTagName('head')[0].appendChild(link);