在这篇文章中,How to add google fonts library in Vuejs application with example 。它包括*多种将google字体Oswald集成到vuejs项目中的方法。
首先,请确保已经安装了vue cli 。 vue cli是创建vuejs应用程序的命令行界面。
npm install -g @vue/cli
这将在你的机器上安装vue cl。运行下面的命令来检查vue命令是否已安装
B:\blog\jswork>vue --version
@vue/cli 4.5.9
创建一个应用程序
vue create vue-google-fonts -n
69 packages are looking for funding
run `npm fund` for details
⚓ Running completion hooks...
📄 Generating README.md...
🎉 Successfully created project vue-google-font.
👉 Get started with the following commands:
$ cd vue-google-font
$ npm run serve
这将创建一个 vuejs 应用程序 vue-google-fonts 基本的应用程序已经创建,包含所有需要的文件和项目结构,准备开始运行。
进入应用程序根目录,用以下方式启动服务器npm start
cd vue-google-font
npm run serve
Vue应用程序正在运行 localhost:8080
使用链接包括谷歌字体Montserrat库
link 标签包括在head部分的public/index.html
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200&display=swap" rel="stylesheet">
在App.vue文件中,在样式部分包括以下样式font-family: Montserrat
<style>
html,body{
font-family: 'Montserrat', sans-serif;
}
</style>
@在vue组件中导入google字体
在这种方法中,我们将在app.vue的样式部分为全局样式表和基于组件的vue文件add google library directly to global stylesheets @import google font url
你可以检查浏览器中显示的输出

本地字体包含在font-face声明中
以上两种方法都是在vuejs应用程序中直接访问google字体CDN,使用这种方法,字体CSS和依赖文件被复制到vue应用程序中。从google font Montserrat url下载font-family资产,下载后解压到src/assets/fonts文件夹,如下图所示
首先在css@font-face 中声明字体名称:App.vue
<style>
@font-face {
font-family: 'Montserrat';
src: local('Montserrat'), url('./assets/fonts/Montserrat-Light.ttf') format('truetype'),
}
</style>
css属性配置如下
.heading{
font-family: "Montserrat", sans-serif;
}
这样,我们就可以托管css文件并将其整合到vuej应用程序中。
总结
在这篇文章中,我们学到了different ways to add google font library in vuejs application
- @导入谷歌字体css
- index.html中的链接属性
- 使用@font-face声明的本地css文件
@import和link属性的方法是在vuejs组件中直接引用cdn文件,因为这是从外部url加载css文件,性能并不理想。最后,托管css文件在性能、依赖性和可维护性方面是很好的方法。