Injecting property defaults into 3rd party Vue com

2019-08-07 19:16发布

问题:

I am using a datepicker component in my project. Basic usage would be like this:

date-picker(language="fr" v-model="date")

There are several attributes which will get repeated each time we need to use a date picker: language for instance.

So I would like to be able to simply do that when a date picker is needed.

date-picker(v-model="date")

And that would default to fr for the language property of the 3rd party library.

Here is what I have tried:

  • A custom component which extends the Datepicket component: Not that great as I need to define a template which contains the original date picker component. That translates to a superfluous wrapper component
  • A plugin? I can only inject properties to the global Vue instance. (pretty new to Vue)
  • Mixin does not apply as I would need to change the 3rd party component

回答1:

Not sure how you extended the component. But this should be elegant enough?

for e.g.

Vue.component("extended-datepicker", {
  extends: vuejsDatepicker,
  props: {
    format: {
      default: "yyyy MMM(MM) dd"
    },
    language: {
        default: fr
    }
  }
});

demo: https://jsfiddle.net/jacobgoh101/5917nqv8/2/


Update for the problem where "single file components are required to provide a template tag"

A Vue component is essentially a JavaScript object with certain properties.

You don't always need to use .vue single file component. In this case, you can just create a .js file that export an object.

For e.g. this ExtendedDatepicker.js would be a valid Vue component

import Datepicker from "vuejs-datepicker";

export default {
  extends: Datepicker,
  props: {
    format: {
      default: "yyyy MMM(MM) dd"
    }
  }
};

demo: https://codesandbox.io/s/9kn29053r