在 Vue js 中使用原型和插件之间的区别?

Jeg*_*B S 5 javascript ecmascript-6 vuejs2

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

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

例如:-

1)创建原型:

import moment from 'moment';
Object.defineProperty(Vue.prototype, '$moment', { value: moment });
Run Code Online (Sandbox Code Playgroud)

2)使用插件将服务合并到其中:

import axios from 'axios';

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

两者都使用原型,并且两种方法都适合我...我只需要知道这两种方法之间的区别...

Vam*_*hna 3

插件应该有一个install像你使用的属性:

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

当你使用插件时你应该​​调用该Vue.use()方法

Vue.use(MyPlugin);
Run Code Online (Sandbox Code Playgroud)

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

在你的情况下,你只是在Vue.

插件主要用于开发要合并到其他 vuejs 项目中的 3rd 方库或资产。

例如,假设您开发了一个可供其他人使用的 vue 组件;

您这样定义一个插件:

import MyComponent from './path'

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

export MyPlugin;
Run Code Online (Sandbox Code Playgroud)

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

import MyComponent from 'MyComponent'


Vue.use(MyComponent);
Run Code Online (Sandbox Code Playgroud)

现在my-component可在任何其他组件中全局使用,并可用作:

<my-component></my-component>my-component>
Run Code Online (Sandbox Code Playgroud)