如何扩展从 npm 包导入的 vue 组件?

Qar*_*Qar 4 vue.js vue-component vuejs2

如果你有一个通过 Node 安装的 vue 组件:

node_modules/vendor/somecomponent.vue
Run Code Online (Sandbox Code Playgroud)

有没有办法修改/扩展这个组件的模板/方法?

更新:

在尝试了下面的示例后,我面临这个问题:

我正在使用https://github.com/eliep/vue-avatar并且我需要用一个道具来扩展它,并且可能稍微修改一下模板。

import {Avatar} from 'vue-avatar'

Avatar = Vue.component('Avatar').extend({
      props: ['nationality']
});

export default {
        components: {
            Avatar
        }, 

       ...
}
Run Code Online (Sandbox Code Playgroud)

结果是 TypeError: Cannot read property 'extend' of undefined

Roy*_*y J 5

貌似没有专门的文档,但是Vue本身extend方法对组件是可用的。您可以覆盖模板并添加方法(以及数据和道具)。

Vue.component('someComponent', {
  template: '<div>hi {{name}} {{one}}</div>',
  data: () => ({
    name: 'original'
  }),
  props: ['one'],
  methods: {
    original: function() {
      this.name = 'original';
    }
  }
});

const myC = Vue.component('someComponent').extend({
  template: '#my-template',
  props: ['two'],
  methods: {
    another: function() {
      this.name = 'another';
    }
  }
});


new Vue({
  el: '#app',
  components: {
    myComponent: myC
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.3/vue.min.js"></script>
<div id='app'>
  <my-component one="arf" two="meow"></my-component>
</div>

<template id="my-template">
  <div>Look, it's {{name}} {{one}} {{two}}
  <button @click="original">Call original</button>
  <button @click="another">Call another</button>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

Avatar似乎是一个组件规范,Vue 将从中创建一个 Component 对象的简单 JavaScript 对象。尝试这个:

Vue.component('originalAvatar', Avatar);
const newAvatar = Vue.component('originalAvatar').extend({
  /* Your spec */
});
Run Code Online (Sandbox Code Playgroud)