How to extend vue component imported from npm package?

偶尔善良 提交于 2019-12-22 10:57:48

问题


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:


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


来源:https://stackoverflow.com/questions/42766697/how-to-extend-vue-component-imported-from-npm-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!