【问题标题】:How to use Vue Plugins Correctly? <PluginName> is not defined如何正确使用 Vue 插件? <PluginName> 未定义
【发布时间】:2023-03-21 22:40:01
【问题描述】:

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

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 未定义

请帮忙?

【问题讨论】:

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


    【解决方案1】:

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

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

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

    这定义了一个要导出的 default 对象,其中包含一个属性 install。当您将此对象导入为AlertPlugin 时,就像您在app.js 中所做的那样,它将生成一个AlertPlugin 对象,该对象具有您在插件文件中定义的install 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-25
      • 2019-09-04
      • 2018-08-24
      • 2018-03-30
      • 2020-04-10
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多