如何扩展从NPM软件包导入的VUE组件



如果您有通过节点安装的vue组件:

node_modules/vendor/somecomponent.vue

有什么方法可以修改/扩展此组件的模板/方法?

更新:

尝试下面的示例后,我将面临此问题:

我正在使用https://github.com/eliep/vue-avatar,我需要用道具扩展它,也许可以修改模板。

import {Avatar} from 'vue-avatar'
Avatar = Vue.component('Avatar').extend({
      props: ['nationality']
});
export default {
        components: {
            Avatar
        }, 
       ...
}

导致TypeError: Cannot read property 'extend' of undefined

它似乎并未具体记录,但是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 */
});

最新更新