因此,我正在使用 Vue 3 创建自定义 Web 组件,以便在任何 Web 应用程序中使用,但由于影子根,在导入字体和 Google Material 图标时遇到了问题。我当前的方法是在注册 Web 组件时将样式表链接标记添加到应用程序标头,它可以工作,但我觉得它破坏了 Web 组件的封装思想,而且我觉得这会影响正在使用的应用程序的样式我的自定义 Web 组件。
这是我当前的实现。
import { defineCustomElement as VueDefineCustomElement, h, getCurrentInstance } from 'vue';
export function register() {
// Icons
loadStylesheet(
'https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200'
);
// Fonts
loadStylesheet('https://fonts.googleapis.com/css2?family=Lato:wght@400;500;600;700&display=swap');
// components
customElements.define('comp', defineCustomElement(comp1));
...
}
export const defineCustomElement = (component) => {
...
return VueDefineCustomElement({
setup() {
... // some data injection
return () => h(component);
},
});
};
// Function to add the stylesheets to applications head tag
function loadStylesheet(href) {
let existingNode = null; // get existing stylesheet node if it already exists:
for (let i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(href) > -1) {
existingNode = document.styleSheets[i].ownerNode;
break;
}
}
if (existingNode) {
return;
} // already exists so don't need to add again
let linkTag = document.createElement('link');
linkTag.rel = 'stylesheet';
linkTag.href = href;
document.getElementsByTagName('head')[0].appendChild(linkTag);
}
在根组件中我做了以下操作
@import url('../index.css');
@import url('https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200');
:host {
font-family: Lato, Arial, Helvetica, sans-serif;
}
我考虑过下载字体并使用它并用 svg 替换图标。不过我觉得这会增加包的大小。
要添加图标,请转到 font Awesome 注册并获取嵌入套件代码,将其插入 HTML 标头部分,然后您可以在网站中搜索图标,插入它们很容易