Vue插件之公共方法封装
-
MyPlugin.install = function (Vue, options) { // 1. 添加全局方法或属性 Vue.myGlobalMethod = function () { // 逻辑... } // 2. 添加全局资源 Vue.directive('my-directive', { bind (el, binding, vnode, oldVnode) { // 逻辑... } // ... }) // 3. 注入组件 Vue.mixin({ created: function () { // 逻辑... } // ... }) // 4. 添加实例方法 Vue.prototype.$myMethod = function (methodOptions) { // 逻辑... } } 初学时,看着有点懵,不知道从哪儿下手,那就一个一个来试试咯
// 创建一个插件文件 test.js let test = {} test.install = function (Vue, options) { Vue.prototype.$msg = 'Hello I am test.js' } export default test // 在main.js中添加 import test from './test' Vue.use(test) // 去其他地方测试下 例如 app.vue created () { console.log('现在的api: ', this.$msg) // 初始化项目时,会打印 Hello I am test.js }, // 第一步尝试成功添加一些方法
// test.js Vue.prototype.$netErr = (tag, err) => { console.log(`Error find in interface ${tag}: ${err}`) Message('请求数据失败,请稍后重试!') }
本文介绍了如何使用Vue.js创建插件,包括添加全局方法、资源和实例方法等。通过具体示例展示了如何在test.js中定义插件并在main.js中引入使用。
1753

被折叠的 条评论
为什么被折叠?



