vue导入字体

541 阅读1分钟

在Vue项目中使用自定义字体(如Mont-Regular字体的OTF文件),你需要通过以下几个步骤来确保字体正确加载并在你的组件中使用。

步骤 1: 将字体文件添加到项目中

首先,将 Mont-Regular.otf src/assets/fonts/ 目录下。

步骤 2: 在 vue.config.js 中配置字体路径(可选)

如果你使用的是 Vue CLI,可以通过修改 vue.config.js 文件来配置静态资源的路径。不过,对于字体文件,直接在CSS中引用通常就足够了。

步骤 3: 在全局或组件的CSS中引入字体

可以在你的全局CSS文件(如 src/assets/styles/global.css)或在单个组件的 <style> 标签中引入字体。

全局引入(推荐)

  1. src/assets/styles/global.css 中添加以下内容:
@font-face {
  font-family: 'Mont-Regular';
  src: url('@/assets/fonts/Mont-Regular.otf') format('opentype');
  font-weight: normal;
  font-style: normal;
}

body {
  font-family: 'Mont-Regular', sans-serif; /* 或者在需要的地方应用这个字体 */
}
  1. 确保在 main.jsmain.ts 中引入了全局CSS文件:
import './assets/styles/global.css';

在组件中引入

如果只想在某个组件中使用这个字体,可以直接在组件的 <style> 标签中定义:

<template>
  <div class="custom-font-text">Hello, World!</div>
</template>

<style scoped>
@font-face {
  font-family: 'Mont-Regular';
  src: url('@/assets/fonts/Mont-Regular.otf') format('opentype');
  font-weight: normal;
  font-style: normal;
}

.custom-font-text {
  font-family: 'Mont-Regular', sans-serif;
}
</style>

步骤 4: 使用字体

现在,可以在Vue组件中使用定义的字体了。例如:

<template>
  <div class="text-with-custom-font">This text uses Mont-Regular font.</div>
</template>

<style scoped>
.text-with-custom-font {
  font-family: 'Mont-Regular', sans-serif;
}
</style>