1、插件的作用
- 插件通常會為 Vue 添加全局功能,一般是添加全局方法/全局指令/過濾器等
- Vue 插件有一個公開方法 install ,通過 install 方法給 Vue 添加全局功能
- 通過全局方法 Vue.use() 使用插件,它需要在你調用 new Vue() 啟動應用之前完成.
2、開發插件並且使用
在項目目錄下創建plugins.js文件,用於寫入插件內容
(function () { const MyPlugin = {} //聲明一個插件對象 MyPlugin.install = function (Vue, options) { // 1. 添加全局方法或屬性 Vue.myGlobalMethod = function () { alert("添加全局方法或屬性") } // 2. 添加全局資源 Vue.directive('my-directive', { inserted: function (el, binding) { el.innerHTML = binding.value } }) // 3. 注入組件選項 Vue.mixin({ created: function () { // 邏輯... } }) // 4. 添加實例方法,可以傳參 Vue.prototype.$myMethod = function () { alert('添加實例方法') } } // 將插件添加到 window 對象中 window.MyPlugin = MyPlugin })()
在index.html中進行引入,並且使用:
- 引入文件
<script src="./plugins.js"></script>
- 通過全局方法
Vue.use()
使用插件
Vue.use(MyPlugin)
- 使用
<!DOCTYPE html> <html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <button v-my-directive="msg"></button> <!--使用指令--> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script src="./plugins.js"></script> <script> Vue.use(MyPlugin) var vm = new Vue( { el: '#app', data: { msg: 'hello' }, // 在 `methods` 對象中定義方法 methods: { } } ) //調用自定義的全局方法,Vue 調用 Vue.myGlobalMethod() // 調用 Vue 實例方法,vm實例調用 vm.$myMethod() </script> </body> </html>
3、axios插件化
axios用於發送請求,但是在項目中時常需要引入,可以利用插件,做成全局的插件,這樣不需要每一個頁面都進行引入
- 在項目目錄下建立對應的插件文件
- 寫對應的實例方法
import axios from 'axios' const MyHttpServer = {} MyHttpServer.install = (Vue) => { axios.defaults.baseURL = 'http://127.0.0.1:8000/api/' //添加實例方法 Vue.prototype.$http = axios } export default MyHttpServer
- 在main.js中全局導入
import MyHttpServer from '@/plugins/http'
Vue.use(MyHttpServer)
- 在需要的地方可以進行使用了
this.$http.post('addUser',data)