Vue创建一个插件

dre*_*oft 0 javascript vue.js vuejs2

我觉得有点像我错过了一些非常简单的东西,但我一直在尝试不同的东西并在整个地方搜索,并且无法弄清楚如何在我的Vue应用程序中使用自定义插件中的方法.

在'vuePlugin.js'中我有类似的东西:

const myPlugin = {};
myPlugin.install = function(Vue, options){
    Vue.myMethod = function(){
        console.log("It worked!");
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的main.js中,我有:

import myPlugin from './js/vuePlugin.js'
Vue.use(myPlugin);
Run Code Online (Sandbox Code Playgroud)

然后在我的App.vue中我有:

export default {
    name: 'app',
    props: {},
    data () {
        return{ someData: 'data' }
    },
    beforeCreate: function(){
        myMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,我得到一个"myMethod未定义"的错误.

我试过说:

var foo = myPlugin();
console.log(foo);
Run Code Online (Sandbox Code Playgroud)

在我的控制台中,我得到一个名为"install"的对象,带有参数:"Exception:TypeError:'caller'和'arguments'是受限制的函数属性,在此上下文中无法访问.在Function.remoteFunction"

所有文档似乎只是展示如何创建插件并"使用"它,但实际上并不是如何访问它中的任何内容.我在这里错过了什么?

Sur*_*amy 6

您必须导出要在vuejs中使用的对象,如下所示

file vuePlugin.js

const myPlugin = {}
myPlugin.install = function (Vue, options) {
  Vue.myMethod = function () {
    console.log('It worked!')
  }
  Vue.prototype.mySecondMethod = function () {
     console.log('My second Method ')
  }
}
export default myPlugin
Run Code Online (Sandbox Code Playgroud)

在调用方法时,您无法直接调用该方法,您必须使用如下所示的代码

file App.vue

export default {
    name: 'app',
    props: {},
    data () {
        return{ someData: 'data' }
    },
    beforeCreate: function(){
        Vue.myMethod(); // call from Vue object , do not directly  call myMethod() 
        this.mySecondMethod() // if you used prototype based method creation in your plugin 
    }
}
Run Code Online (Sandbox Code Playgroud)

希望它会对你有所帮助