4

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

1 Answer 1

5

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 */
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! What about extending plugins? Is that the same procedure?
I am a little bit confused on how to use your example, in my situation. I've updated the question with my issue.
@Qar If the Avatar object is itself a component, you would do Avatar.extend(...) rather than getting it by name from Vue.
yeah thought so, too, but getting a "TypeError: __WEBPACK_IMPORTED_MODULE_1_vue_avatar__.Avatar.extend is not a function" when trying that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.