sync.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict';
  2. exports.__esModule = true;
  3. var SYNC_HOOK_PROP = '$v-sync';
  4. /**
  5. * v-sync directive
  6. *
  7. * Usage:
  8. * v-sync:component-prop="context prop name"
  9. *
  10. * If your want to sync component's prop "visible" to context prop "myVisible", use like this:
  11. * v-sync:visible="myVisible"
  12. */
  13. exports.default = {
  14. bind: function bind(el, binding, vnode) {
  15. var context = vnode.context;
  16. var component = vnode.child;
  17. var expression = binding.expression;
  18. var prop = binding.arg;
  19. if (!expression || !prop) {
  20. console.warn('v-sync should specify arg & expression, for example: v-sync:visible="myVisible"');
  21. return;
  22. }
  23. if (!component || !component.$watch) {
  24. console.warn('v-sync is only available on Vue Component');
  25. return;
  26. }
  27. var unwatchContext = context.$watch(expression, function (val) {
  28. component[prop] = val;
  29. });
  30. var unwatchComponent = component.$watch(prop, function (val) {
  31. context[expression] = val;
  32. });
  33. Object.defineProperty(component, SYNC_HOOK_PROP, {
  34. value: {
  35. unwatchContext: unwatchContext,
  36. unwatchComponent: unwatchComponent
  37. },
  38. enumerable: false
  39. });
  40. },
  41. unbind: function unbind(el, binding, vnode) {
  42. var component = vnode.child;
  43. if (component && component[SYNC_HOOK_PROP]) {
  44. var _component$SYNC_HOOK_ = component[SYNC_HOOK_PROP],
  45. unwatchContext = _component$SYNC_HOOK_.unwatchContext,
  46. unwatchComponent = _component$SYNC_HOOK_.unwatchComponent;
  47. unwatchContext && unwatchContext();
  48. unwatchComponent && unwatchComponent();
  49. }
  50. }
  51. };