vue.js - 如何调用我的 Vue.js 插件中声明的函数

标签 vue.js plugins

我编写了一个 Vue.js 插件来全局访问 Vue 函数:

const MyPlugin = {
  install (Vue, options) {
    Vue.myFunction = function () {     
      console.log('Test')
    }
  }
}
export default { MyPlugin }

并将其包含在 main.js 文件中:

import MyPlugin from './plugins/my-plugin.js'
Vue.use(MyPlugin)

但是,当我尝试从这样的 Vue 组件调用 myFunction 时:

<a href="#">
  <i class="fa fa-gears fa-fw"></i>  {{ myFunction() }} <span class="fa arrow"></span>
</a>

它给了我以下错误:

Property or method "myFunction" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option or for class-based components, by initializing the property

我需要做什么才能访问 vue 组件中的“myFunction”?

最佳答案

如果您尝试从模板访问全局方法,则该方法需要在 Vue 组件的实例上可用。因此,您需要在 Vue.prototype 对象上设置 myFunction 函数:

install (Vue, options) {
  Vue.prototype.myFunction = function () {     
    console.log('Test')
  }
}

See the docs on writing plugins.


正如您在文档中所看到的,在这些类型的全局函数前面添加 $ 是一种常见的约定,以便更轻松地将它们与 Vue 实例上的其他方法区分开来。因此,在您的情况下,最好将函数设置为 Vue.prototype.$myFunction

关于vue.js - 如何调用我的 Vue.js 插件中声明的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633886/

相关文章:

html - Vuetify嵌套数据表列宽问题

javascript - 我应该如何处理 Electron 中面向用户的插件?

Java - 动态加载类

c++ - 让多线程程序的两个 "deep"部分相互通信的模式是什么?

macos - 尝试在Mac OS El Capitan中安装ElasticSearch插件时出现问题

javascript - 结合 vuejs v-repeat 和 php foreach 循环?

vue.js - 我是否需要检查观察者中新旧值之间的不平等?

javascript - 包含标签的字符串在 <td> 内无法正确呈现

javascript - 带有 bootstrap-vue b-table 的 V 模型

plugins - CodeIgniter - 如何创建插件系统?