简体   繁体   English

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

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

I'm trying to refactor some commonly used functions into a globally available Util plugin for my app.我正在尝试将一些常用功能重构为我的应用程序的全局可用 Util 插件。 I followed the instructions from the docs and this question , but I'm not sure how to use it the functions in the template and Vue keeps complaining about an undefined method.我按照文档这个问题的说明进行操作,但我不确定如何使用模板中的函数,并且 Vue 一直抱怨未定义的方法。 Ideally I just want to call isEmpty from any child component.理想情况下,我只想从任何子组件调用isEmpty

util.js实用程序.js

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

Also tried:也试过:

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

main.js 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')

None of the below work.以下都不起作用。 The error thrown is TypeError: Cannot read property 'isEmpty' of undefined抛出的错误是TypeError: Cannot read property 'isEmpty' of undefined

component template组件模板

<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>

You are almost done, are missing of prototype .你快完成了,缺少prototype Try this:尝试这个:

utils.js实用程序.js

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

Component零件

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

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

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

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