VueJS + Webpack +动态CSS

时间:2018-05-16 11:04:19

标签: css webpack vue.js

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

短片

  • 应用程序启动并通过url address
  • 向CSSE文件名的后端服务器提交请求
  • Apllication从后端服务器获取带有css文件名参数的响应

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

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

Vue组件的简短摘录:

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

感谢任何想法。

1 个答案:

答案 0 :(得分:1)

您可以将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);