首页 > 解决方案 > 无法通过插件访问 Vue.js 全局函数

问题描述

我正在尝试将一些常用功能重构为我的应用程序的全局可用 Util 插件。我按照文档这个问题的说明进行操作,但我不确定如何使用模板中的函数,并且 Vue 一直抱怨未定义的方法。理想情况下,我只想isEmpty从任何子组件调用。

实用程序.js

export default {
  install(Vue, options) {
      Vue.isEmpty = function (object) {
        return false // dummy function for now to check if method works
      }
  }
}

也试过:

Util.install = function (Vue, options) {
  Vue.isEmpty = function () {
    ...
  }
  // this doesn't work either
  // Vue.prototype.$isEmpty = function (object) {
  // return false
  //  }
}

main.js

import util from './components/shared/util.js'
import comp from './components/shared/myComponent.js'
// Vue.component('util', util) this doesn't work
Vue.use(util)

const app = new Vue({
...
components: {
    comp
}).$mount('#app')

以下都不起作用。抛出的错误是TypeError: Cannot read property 'isEmpty' of undefined

组件模板

<p v-if="util.isEmpty(license)" class="margin-0">N/A</p>
<p v-if="Vue.isEmpty(license)" class="margin-0">N/A</p>
<p v-if="isEmpty(license)" class="margin-0">N/A</p>

标签: javascriptvue.jsvuejs2

解决方案


您快完成了,缺少prototype. 尝试这个:

实用程序.js

export default {
  install(Vue, options) {
      Vue.prototype.isEmpty = function (object) {
        return false // dummy function for now to check if method works
      }
  }
}

零件

<p v-if="isEmpty(license)" class="margin-0">N/A</p>

这里是一个例子:https ://codesandbox.io/s/vue-template-tdx00


推荐阅读