Skip to content

Create Vue components whose nested prop changes map to a global side effect

License

Notifications You must be signed in to change notification settings

egoist/side-effect

Repository files navigation

side-effect NPM version NPM downloads Build Status

Heavily inspired by react-side-effect.

Features

  • Light-weight: 500 bytes gzipped
  • Simple: Just a component
  • Works just as well with isomorphic apps

Install

$ npm install --save side-effect

Example

It gathers current props across the whole tree before passing them to side effect. For example, this allows you to create <body-style :set-style> component like this:

<!-- root component -->
<body-style :set-style="{backgroundColor: 'red'}">
  <some-component></some-component>
</side-effect>

<!-- some-component -->
<body-style :set-style="{backgroundColor: 'yellow'}">
  <input @input="updateColor" />
</side-effect>

Create a side-effect component named BodyStyle for mutating body style from different level of nesting with innermost winning:

import withSideEffect from 'side-effect'

const BodyStyle = {
  name: 'body-style',
  render(h) {
    if (!this.$slots.default) return h()
    return this.$slots.default[0]
  }
}

function reduceInstancesToState(vms) {
  const style = {}
  for (const vm of vms) {
    Object.assign(style, vm.setStyle)
  }
  return style
}


function handleStateChangeOnClient(style) {
  for (const key in style) {
    document.body.style[key] = style[key]
  }
}

export default withSideEffect(
  reduceInstancesToState,
  handleStateChangeOnClient
)(BodyStyle)

Now, it's ready to go: https://side-effect.surge.sh

Server-side Usage

The API is exactly the same as react-side-effect, call rewind() after rendering.

withSideEffect(
  reduceInstancesToState,
  handleStateChangeOnClient,
  mapStateOnServer
)(VueComponent)

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

License

MIT © EGOIST

About

Create Vue components whose nested prop changes map to a global side effect

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published