javascript - 无法通过插件访问 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>
解决方案
您快完成了,缺少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>
推荐阅读
- css - 如何使用 CSS 使表格具有响应性
- javascript - 当我需要运行时如何调用函数Javascript?
- python - Python Selenium:从下拉列表中获取值
- python - 如何使用字典/json在yaml中添加'-'?
- git - 如何解决 git 错误:服务器不允许请求未公布的对象 3a2ceef391af73994dfeb0d8ef57ed6a52ef4238?
- android - 更改 CardView 阴影颜色
- c# - 如何在带有 Razor 页面的 ASP.NET Core 2.1 中使用或处理不是为并发设计的服务器端 SDK
- python - 关于 Python 的 2 个问题:已创建表 & 无法在行中找到重复项
- java - 在我的 JavaFx 应用程序上随机按下 Enter 键会触发错误的按钮操作
- r - 股票相关矩阵 Quantmod