【问题标题】:Unable to access Vue.js global function through plugin无法通过插件访问 Vue.js 全局函数
【发布时间】:2020-01-11 12:41:16
【问题描述】:

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

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

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    您几乎完成了,缺少prototype。试试这个:

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

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多