繁体   English   中英

无法通过插件访问 Vue.js 全局函数

[英]Unable to access Vue.js global function through plugin

我正在尝试将一些常用功能重构为我的应用程序的全局可用 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>

你快完成了,缺少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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM