修改扩展的Vue组件的mount()钩子

时间:2019-07-23 09:52:05

标签: javascript vue.js nuxt.js

我正在构建的系统基于Nuxt。 我已经通过使用插件技术创建了一些全局组件,其中导入和扩展了来自第三方npm包的其他组件,因为我不想修改原始组件。 这是后者的简化源代码:

// simplified version of the component from 3-rd party npm package
<script>
  import LibObj from 'someJSLib'

  export default {
    data() {
      return {
        dataField: null,
      }
    },
    mounted() {
      let that = this
      let initFunc = function (initParam) {

        let actionParam = function (initParam) {
          /* some local generic js code consuming initParam and producing value*/
          return value
        }

        let actionFunc = function (actionParam) {
          actionObj = new LibObj()
          actionObj.listen('event', function(){})
          actionObj.init()
          that.dataField = actionObj // this object reference is "exported" to vue component's data field
        };
        // that.actionFunc = actionFunc // this line of code is absent but I would like have it here


        let condition = function () {/* some local generic js code */}
        if (condition) {
          actionFunc(condition.id);
        }

        /* some more of local generic js code */

      };

      initFunc(cssSelectorString);

    },
  }
</script>

这是到目前为止我尝试过的:

// simplified version of the file where I register and extend the component above^
// no the logic doing any valuable stuff but rather demonstration of the framework of intentions
import Vue from "vue";
import ExternalComponent from 'ExternalNPMPackage';

Vue.component("ExtendedComponent", {
  extends: ExternalComponent,
  methods: {
    myMethod: function() {
      /* some logic somehow interacting with the scopes of the functions declared in the ExternalComponent */
    }
  },
  created: function() {
    console.log("created() in extended component");
    // this function is called before the code in the mounted() hook of ExternalComponent
  },
  mounted: function() {
    console.log("mounted() in extended component");
    // this function is called after the code in the mounted() hook of ExternalComponent
  },
});

问题在于,原始组件的所有逻辑都在“已安装”挂钩中实现。 在我自己的组件中,我真的感到缺乏actionFunc作为组件的数据字段的引用。为此,我只添加that.actionFunc = actionFunc。 我已经尝试过扩展“挂接”钩子,并在分配的“拦截”过程中添加一些逻辑,但是没有运气可以访问在那里定义的任何函数的作用域。

我还能采取什么其他步骤来实现这种代码注入,从而避免将所有代码愚蠢地复制到我自己的组件中?

0 个答案:

没有答案