我写了一个插件:
var MyCoolVuePlugin = {
install(Vue) {
Vue.prototype.doStuff = function() {
console.log("I'm a useless plugin")
}
}
}
export default MyCoolVuePlugin;
在我的main.js
中,我的前端启动并创建了Vue实例,我包括了我的插件:
import Vue from 'vue';
import App from './App';
import MyCoolVuePlugin from './plugin';
Vue.use(MyCoolVuePlugin);
window.vApp = new Vue({
el: '#app',
router: Router,
components: { App },
template: '<App/>'
});
然后在我的App.vue
里,我有这样的东西:
<template>
<div id="app">
<h1>Is Anybody There</h1>
<some-other-component />
</div>
</template>
<script>
import SomeOtherComponent from "./components/SomeOtherComponent";
export default {
name: "App",
components: {
"some-other-component": SomeOtherComponent
},
data() {
...
},
mounted() {
// How do I access my Vue plugin
// I can do:
vApp.doStuff();
// Or I can do:
this.$parent.doStuff();
}
};
</script>
<style lang="scss">
...
</style>
如何访问我的Vue插件,如mounted
的App.vue函数所示?当我问“我怎么做”时,我的意思是什么是正确的,推荐的方式?也许我在搜索方面失败了,但到目前为止,我还没有找到与完成这一任务相关的文档。
发布于 2018-05-31 11:56:00
当您使用Vue.use()
安装插件时,它将调用插件的安装方法,在该插件中要向prototype
of Vue
添加一个方法。
这允许您使用this.doStuff()
在任何组件中访问此方法。
所以您可以在挂载的钩子中访问它,如
mounted() {
this.doStuff();
}
我建议您用$
前缀命名要附加在原型上的属性或方法。
因此,Vue.prototype.$doStuff
可以以this.$doStuff
的形式在任何组件中访问。这只是个惯例。
https://stackoverflow.com/questions/50623477
复制相似问题