如何扩展从NPM包导入的Vue组件?

4
如果您有一个通过Node安装的Vue组件:
node_modules/vendor/somecomponent.vue

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

更新:

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

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

import {Avatar} from 'vue-avatar'

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

export default {
        components: {
            Avatar
        }, 

       ...
}

在编程中出现了错误:TypeError: 无法读取未定义的属性 'extend'


1
看起来你可以将它用作mixin:http://012.vuejs.org/guide/extending.html - ceejayoz
1个回答

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
  }
});
<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>

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

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

1
谢谢!扩展插件怎么样?是同样的过程吗? - Qar
我有点困惑如何在我的情况下使用你的示例。我已经更新了问题并陈述了我的问题。 - Qar
如果Avatar对象本身是一个组件,你应该使用Avatar.extend(...)而不是从Vue中按名称获取它。 - Roy J
是的,我也这么想,但是尝试后出现了“TypeError: WEBPACK_IMPORTED_MODULE_1_vue_avatar.Avatar.extend is not a function”错误。 - Qar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接