我编写了一个 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/