如何在 VueJS (SPA) 应用程序上动态加载 CSS 文件?
短场景
- 应用启动并通过url地址向后端服务器提交CSS文件名请求
- 应用程序使用 css 文件名参数从后端服务器获取响应
然后我需要通过响应数据调用一些加载新 CSS 文件的东西。
我们将其用于网站品牌推广(CSS 取决于实际域 - 但网站安装在一台主机上)。此 CSS 文件可以位于我们的服务器 (/assets/css/xx.css) 或其他服务器上。
Vue 组件的简短片段:
loadCssRequest(location.href).then(function(reponse){
// something whats load css by response.css_code
});
感谢您的任何想法。
最佳答案
你可以在组件的头部注入(inject)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);
关于css - VueJS + Webpack + 动态 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50369205/