Rangy 库的 Vue 错误:“...”不是函数(但仅在钩子内部)

Vue error with Rangy library: "..." is not a function (but only inside hooks)

对于 Vue 组件,我使用 Rangy library 来突出显示文本中的单个单词。如果从 methods 对象内的任何方法调用 Rangy,这工作正常:

let applier = rangy.createClassApplier('some-class');
applier.toggleRange(range);

但有时我需要在页面加载时恢复某个状态,所以我尝试在 createdmounted 挂钩中使用相同的方法。这行不通。

现在,我的组件中脚本的第一行如下所示:

import _ from 'lodash';
import rangy from 'rangy';
import 'rangy/lib/rangy-classapplier';

export default {

    mounted: function() {
        // Leave function if there is no data in DB to be restored
        if (_.isEmpty(this.mostRecentAnswers))
            return;

        else {
            // ERROR
            let applier = rangy.createClassApplier('some-class');
            // ...
        }
    }
    // ...
}

错误信息是TypeError: rangy__WEBPACK_IMPORTED_MODULE_2___default.a.createClassApplier is not a function at VueComponent.mounted

我将 Vue 与 Laravel 和 Laravel Mix(它是 Webpack 的包装器)一起使用。

我的代码有什么问题?注意我还导入了 Lodash 并在 hook 中使用它没有任何错误。

我必须使用 rangy.init() 来初始化 Rangy,如果它还没有被初始化的话: https://github.com/timdown/rangy/wiki/Rangy-Object#rangyinit

我建议用它制作一个 Vue 插件以使其更容易:

// plugins/vue-rangy.js

import rangy from 'rangy'

const VueRangy = {
  install (Vue, options) {
      if (options.hasOwnProperty('init') && options.init) {
        rangy.init()
      }

      Vue.prototype.$rangy = rangy
  }
}

export default VueRangy

然后像使用任何其他插件一样使用它:

import VueRangy from 'plugins/vue-rangy'

Vue.use(VueRangy, {
  init: true
})

然后只需在您的组件中使用 this.$rangy