DAY20 | 跟 Vue.js 認識的30天 - Vue 插件(Plugin)

這一篇說實在的,現在的我還不能寫出有用的插件,所以這一篇筆記主要也是學習使用別人寫好的插件。

使用插件

1
2
3
Vue.use('PluginName', {
//options
})

使用別人寫好的插件

插件 : VueAxios

1
2
3
4
5
6
7
8
import Vue from 'vue'
//必須先載入 axios 跟 VueAxios
//VueAxios 的目的是讓 axios 被 Vue 整合(加在 Vue 原型中),確保所有模組都可以使用 axios
import axios from 'axios'
import VueAxios from 'vue-axios'

//使用 Vue.use() 來讓 Vue 可以使用該 VueAxios 插件
Vue.use(VueAxios, axios)

其實在使用別人寫好的插件時,都會附使用說明,就照著說明使用即可。

就目前而言,比較常用的 Vue 插件就是 Vue-router 跟 Vuex ,但因為這2個插件只要檢測到存在 Vue 這個變量後,就會自動調用 Vue.use() ,所以不需要額外寫 Vue.use() ,但必須注意如果是使用 CommonJS 模塊化,仍得使用 Vue.use()

開發插件

可以將比較常用或可複用的方法寫在 Plugin 裡做整合,之後再透過 Vue.use() 一次性載入到專案中使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const MyPlugin = {
install(Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
//內容
console.log(Vue, options)
}

// 2. 全局 directive
Vue.directive('my-directive', {
//內容
bind(el,binding,vnode){
console.log(Vue, options)
}
})

// 3. 全局 mixin
Vue.mixin({
//內容
created(){
console.log(Vue, options)
}
})

// 4. 添加實例方法
Vue.prototype.$myMethod = function (methodOptions) {
//內容
console.log(Vue, options)

}
}
}

Demo

See the Pen DAY20 | 跟 Vue.js 認識的30天 - Vue 插件(Plugin) by Celeste6666 (@celeste6666) on CodePen.

參考資料

Vue.js - 插件