# Vue 引入字体
在 Vue 项目中引入字体可以通过多种方式实现。以下是几种常见的方法,并附带示例代码和解释说明。
## 方法一:通过 CSS @font-face 引入
这是最常用的方法之一,通过 `@font-face` 规则在 CSS 文件中定义字体。
### 示例代码
1. **创建或编辑项目的全局样式文件**(如 `src/assets/styles/global.css` 或 `src/assets/styles/main.css`):
```css
/* src/assets/styles/global.css */
@font-face {
font-family: 'MyCustomFont';
src: url('./fonts/MyCustomFont.woff2') format('woff2'),
url('./fonts/MyCustomFont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
body {
font-family: 'MyCustomFont', sans-serif;
}
main.js
中引入全局样式文件:// src/main.js
import Vue from 'vue';
import App from './App.vue';
import './assets/styles/global.css'; // 引入全局样式文件
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
}).$mount('#app');
@font-face
规则用于定义自定义字体。你需要指定字体名称、字体文件路径和格式。body
标签中使用该字体,确保整个页面都使用你引入的字体。Google Fonts 提供了非常方便的方式引入在线字体。
public/index.html
中添加 Google Fonts 链接:<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue App</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="app"></div>
</body>
</html>
<template>
<div class="app-container">
<h1>Hello World</h1>
</div>
</template>
<script>
export default {
name: 'App'
};
</script>
<style scoped>
.app-container {
font-family: 'Roboto', sans-serif;
}
</style>
index.html
中引入 Google Fonts 的链接后,可以在任何地方使用该字体。有些字体库可以直接通过 npm 安装并使用。
npm install typeface-roboto
main.js
中引入字体库:// src/main.js
import 'typeface-roboto';
import Vue from 'vue';
import App from './App.vue';
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
}).$mount('#app');
<template>
<div class="app-container">
<h1>Hello World</h1>
</div>
</template>
<script>
export default {
name: 'App'
};
</script>
<style scoped>
.app-container {
font-family: 'Roboto', sans-serif;
}
</style>
main.js
中引入字体库即可全局使用。以上是几种在 Vue 项目中引入字体的常见方法。你可以根据具体需求选择最适合的方式。
上一篇:vue3 流程图组件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站