Vue 第三方庫的使用
1. 前言
本小節(jié)我們將帶大家學(xué)習(xí):如何在項目中使用第三方庫。在日常的開發(fā)中,我們正在大量地使用第三方庫。學(xué)會使用第三方庫,可以說是前端工程師最基本的技能。其實,使用第三方庫非常簡單,絕大部分庫的文檔中都會教我們?nèi)绾问褂谩?/p>
接下來我們用幾個案例來學(xué)習(xí)使用第三方庫。
2. ElementUI 的使用
我們打開 ElementUI 的官網(wǎng),根據(jù)官網(wǎng)的教程一步步學(xué)習(xí)。
2.1 安裝
在 Vue-cli 創(chuàng)建的項目中,我們可以使用以下命令進行安裝:
npm install element-ui -S
也可以通過 CDN 的方式在頁面上直接引入:
<!-- 引入樣式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入組件庫 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
2.2 使用
在 main.js 中寫入以下內(nèi)容:
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
Vue.config.productionTip = false;
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
Vue.use(ElementUI);
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
此時,我們已經(jīng)可以在項目中使用 Element 給我們提供的各種組件了。
我們可以改造 ‘views/Home.vue’ 中的內(nèi)容:
<template>
<div class="home">
<h1>使用 icon 組件</h1>
<i class="el-icon-edit"></i>
<i class="el-icon-share"></i>
<i class="el-icon-delete"></i>
<h1>使用 button 組件</h1>
<el-button>默認(rèn)按鈕</el-button>
<el-button type="primary">主要按鈕</el-button>
<el-button type="success">成功按鈕</el-button>
<el-button type="info">信息按鈕</el-button>
<el-button type="warning">警告按鈕</el-button>
<el-button type="danger">危險按鈕</el-button>
</div>
</template>
<script>
export default {
name: "Home",
components: {}
};
</script>
3. Lodash 的使用
同樣地,要使用 Lodash,我們需要先通過 npm install --save lodash
安裝 Lodash。在使用 lodash 之前,通過 import _ from "lodash"
引入 Lodash 包。此時,我們就可以在項目中使用 Lodash 給我們提供方法了:
<script>
import _ from "lodash";
export default {
name: "Home",
created() {
const str = _.join(["a", "b", "c"], "~");
console.log(str);
},
components: {}
};
</script>
4. 小結(jié)
本節(jié)我們帶大家學(xué)習(xí)了如何在項目中使用第三方庫。在使用第三方庫之前,我們需要先通過 npm install
安裝第三方庫,然后在項目中利用 import 加載第三方庫。