Vue.js将插件变量传递给自定义组件

时间:2020-05-12 19:00:36

标签: vue.js vuejs2 vue-component

我是Vue.js的新手,我正在尝试创建我的第一个插件(非常简单),以便能够从我的应用程序中按如下方式调用它:

app.js

Vue.use(Pluginify, { option1: 1, option2: 2 });

以下是我遇到的问题,我在插件的index.js文件中有一个名为configuration的变量,该变量是我传递给{{1}的第二个参数}函数,问题是我需要将该变量传递给我正在创建的自定义组件,但不能。请您能帮我,这是我到目前为止的结构:

index.js

Vue.use

我有一个名为Plugin的组件,该组件为空,但我需要它包含配置对象以便将来使用其值。

Plugin.vue

import Vue from 'vue';
import Plugin from './Plugin';
import { isObject } from 'lodash';

export const instance = new Vue({
  name: 'Plugin',
});

const Pluginify = {
  install(Vue, configuration = {}) { // This variable here, I need to pass it to the ```Plugin.vue``` component
    Vue.component('plugin', Plugin);

    const pluginify = params => {
      if (isObject(params)) {
        instance.$emit('create', params);
      }
    };

    Vue.pluginify = pluginify;
    Vue.prototype.$pluginify = pluginify;
  }
};

export default Pluginify;

非常感谢您

3 个答案:

答案 0 :(得分:1)

似乎已经在create事件触发后添加了此侦听器

  mounted() {
    instance.$on('create', this.create);
  },

您可以像这样在插件中使用全局变量...

Vue.prototype.$pluginifyConfig = configuration;

,然后您可以在插件或其他任何地方使用this.$pluginifyConfig进行调用。

但是那污染了全球范围

答案 1 :(得分:1)

也许这可以帮助:

const Plugin = {
  template: '<div>Plugin</div>',
  data() {
    return {
        a: 'a data'
    };
  },
  mounted() {
    console.log(this.a);
    console.log(this.message);
  }
};

const Pluginify = {
    install(Vue, options) {
    Vue.component('plugin', {
      extends: Plugin,
      data() {
        return {...options}
      }
    });
  }
};

Vue.use(Pluginify, {message: 'hello, world!'});

new Vue({
    el: '#app'
});

答案 2 :(得分:0)

好,我已经达到了以下目标:

index.js

const Pluginify = {
  install(Vue, configuration = {}) {
    /**
     * Default plugin settings
     *
     * @type {Object}
     */
    this.default = configuration;

....

因此在我的Plugin.vue组件中:

import * as plugin from './index';

因此,我可以在组件的任何方法中调用配置参数,如下所示:

...
  mounted() {
    console.log(plugin.default.option1);
  },
...

我希望我能为遇到类似问题的任何人提供帮助。