如何调用从 Vuejs 实例声明的函数?

How to call functions declared out of a Vuejs instance?

这是一个伪代码来说明我的问题。当脚本为运行时,会遇到func1 is not defined的错误。我该怎么做?

app.js

require ('./helper');
new Vue ({
el: "#app",

created: function () {
func1()
}
});

helper.js

module.exports = function () {
  $.notify('Hi', {
    position: "bottom right",
    className: "success"
  });
};

提前致谢!

您可能必须将导入的函数保存到 app.js 文件中的变量中。这取决于您使用的捆绑器(例如 browserify 或 webpack 或其他)。在传递给 Vue 的参数对象之外声明的函数应该可以访问:

// app.js
var func1 = require('./helper');
new Vue ({
    el: "#app",

    created: function () {
        func1();
    }
});

在您的 helpers.js 中,您需要引用 jQuery。您可以包含该库(jQuery$ 将在 window 对象上全局可用)或像下面的示例一样,从 https://www.npmjs.com/package/jquery 安装它并将它与你自己的代码。

// helper.js
var $ = require('jquery');

module.exports = function () {
    $.notify('Hi', {
        position: "bottom right",
        className: "success"
    });
};

如果要在多个组件的创建方法中调用此函数,可以创建一个mixin,然后将其传递给特定的组件。

//YourMixin.js
new Vue({
  created: function () { ... }
})

//Component
let mixin = require('YourMixin')

new Vue({
  mixins: [mixin],
  ...
})