怎么把link加载到 head
时间: 2024-01-13 11:05:42 浏览: 29
要将 `<link>` 元素加载到 `<head>` 标签中,可以使用 DOM API 中的 `document.head` 属性。以下是将 `<link>` 元素加载到 `<head>` 标签中的示例代码:
```javascript
import { onMounted, onUnmounted } from "vue";
const props = defineProps<{
components: any[];
style?: string;
}>();
let linkElement = null;
onMounted(() => {
if (props.style) {
linkElement = document.createElement("link");
linkElement.rel = "stylesheet";
linkElement.href = props.style;
document.head.appendChild(linkElement);
}
});
onUnmounted(() => {
if (linkElement) {
document.head.removeChild(linkElement);
linkElement = null;
}
});
```
在 `onMounted` 钩子函数中,首先创建 `<link>` 元素,并设置相关属性。然后,使用 `document.head.appendChild(linkElement)` 将 `<link>` 元素添加到 `<head>` 标签中。
在 `onUnmounted` 钩子函数中,检查 `linkElement` 是否存在,如果存在,则使用 `document.head.removeChild(linkElement)` 将 `<link>` 元素从 `<head>` 标签中移除。
这样,通过动态创建 `<link>` 元素并将其添加到 `<head>` 标签中,可以实现动态加载 CSS 文件。请确保 `props.style` 的值是正确的 CSS 文件路径。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)