How to extend vue component imported from npm pack

2019-05-25 15:55发布

If you have a vue component that is installed via Node :

node_modules/vendor/somecomponent.vue

Is there any way to modify/extend the template/methods of this component?

Update:

After trying out the example below, I'm facing this issue:

I am using https://github.com/eliep/vue-avatar and I need to extend this with a prop, and maybe amend the template a bit.

import {Avatar} from 'vue-avatar'

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

export default {
        components: {
            Avatar
        }, 

       ...
}

Results in TypeError: Cannot read property 'extend' of undefined

1条回答
老娘就宠你
2楼-- · 2019-05-25 16:37

It doesn't appear to be documented specifically, but the extend method of Vue itself is available to components. You can override the template and add methods (and data and props).

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 appears to be a component spec, the simple JavaScript object that Vue will create a Component object from. Try this:

Vue.component('originalAvatar', Avatar);
const newAvatar = Vue.component('originalAvatar').extend({
  /* Your spec */
});
查看更多
登录 后发表回答