如何正确使用Vue插件? <pluginname>未定义

时间:2017-10-11 14:52:44

标签: javascript ecmascript-6 vue.js vuejs2 es6-modules

我正在学习制作基于https://vuejs.org/v2/guide/plugins.html的Vue插件, 这是我的简单代码:

plugin1.js:

AlertPlugin.install = function (Vue, options) {
    Vue.prototype.$classicalert = function (message) {
        alert(message)
    };
};

app.js:

window.Vue = require('vue');
import AlertPlugin from './plugin1.js'
Vue.use(AlertPlugin);

const app = new Vue({
    el: '#app',
    render: h => h(Main)
});

当我试图运行它时,网页变为空白,错误 AlertPlugin未定义

请帮帮忙?

1 个答案:

答案 0 :(得分:1)

plugin1.js文件中,您正在尝试设置install对象的AlertPlugin属性,该对象(如错误所示)未定义。

您的plugin1.js文件应如下所示:

export default {
  install: function (Vue, options) {
    Vue.prototype.$classicalert = function (message) {
      alert(message)
    };
  }
}

这定义了要导出的default对象,其中包含属性install。当您将此对象导入AlertPlugin时,就像在app.js中一样,它会生成AlertPlugin对象,其中包含您在插件中定义的install属性。 s档。