sfc.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Create a basic component with common options
  3. */
  4. import '../../locale';
  5. import { camelize } from '..';
  6. import { SlotsMixin } from '../../mixins/slots';
  7. import Vue from 'vue';
  8. var arrayProp = {
  9. type: Array,
  10. "default": function _default() {
  11. return [];
  12. }
  13. };
  14. var numberProp = {
  15. type: Number,
  16. "default": 0
  17. };
  18. function defaultProps(props) {
  19. Object.keys(props).forEach(function (key) {
  20. if (props[key] === Array) {
  21. props[key] = arrayProp;
  22. } else if (props[key] === Number) {
  23. props[key] = numberProp;
  24. }
  25. });
  26. }
  27. function install(Vue) {
  28. var name = this.name;
  29. Vue.component(name, this);
  30. Vue.component(camelize("-" + name), this);
  31. } // unify slots & scopedSlots
  32. export function unifySlots(context) {
  33. // use data.scopedSlots in lower Vue version
  34. var scopedSlots = context.scopedSlots || context.data.scopedSlots || {};
  35. var slots = context.slots();
  36. Object.keys(slots).forEach(function (key) {
  37. if (!scopedSlots[key]) {
  38. scopedSlots[key] = function () {
  39. return slots[key];
  40. };
  41. }
  42. });
  43. return scopedSlots;
  44. } // should be removed after Vue 3
  45. function transformFunctionComponent(pure) {
  46. return {
  47. functional: true,
  48. props: pure.props,
  49. model: pure.model,
  50. render: function render(h, context) {
  51. return pure(h, context.props, unifySlots(context), context);
  52. }
  53. };
  54. }
  55. export var useSFC = function useSFC(name) {
  56. return function (sfc) {
  57. if (typeof sfc === 'function') {
  58. sfc = transformFunctionComponent(sfc);
  59. }
  60. if (!sfc.functional) {
  61. sfc.mixins = sfc.mixins || [];
  62. sfc.mixins.push(SlotsMixin);
  63. }
  64. if (sfc.props) {
  65. defaultProps(sfc.props);
  66. }
  67. sfc.name = name;
  68. sfc.install = install;
  69. return sfc;
  70. };
  71. };