我需要在vue js项目中使用简单的跟踪服务...

在我的app.js中,我可以通过两种方式使用它...

例如:-

1)创建一个原型(prototype):

import moment from 'moment';
Object.defineProperty(Vue.prototype, '$moment', { value: moment });

2)使用插件将服务合并到其中:
import axios from 'axios';

export default {
  install: function(Vue,) {
    Object.defineProperty(Vue.prototype, '$http', { value: axios });
  }
}

两者都使用原型(prototype),并且两种方式都对我有用...我只需要知道这两种方法之间的区别...

最佳答案

插件应具有您所使用的install属性:

const MyPlugin = {
    install: function(Vue,) {
        Object.defineProperty(Vue.prototype, '$http', { value: axios });
    }
}

当您使用插件时,应调用Vue.use()方法
Vue.use(MyPlugin);

this.just调用插件上的install方法

在您的情况下,您只是在Vue上设置原型(prototype)。

插件主要用于开发第三方库或 Assets ,以将其合并到othe vuejs项目中。

例如,假设您开发了一个vue组件,该组件可以被其他人使用。

您可以这样定义插件:
import MyComponent from './path'

const MyPlugin = {
    install: function(Vue,) {
        Vue.component('my-component', MyComponent);
    }
}

export MyPlugin;

现在,当您在npm上发布插件时,其他人可以按以下方式使用您的组件:
import MyComponent from 'MyComponent'


Vue.use(MyComponent);

现在,my-component在任何其他组件中都可以全局使用,并且可以用作:
<my-component></my-component>my-component>

09-30 13:27
查看更多