Vue Extend Reactive
Vue helper to extend reactive object.
Notice
This helper is compatible with both Vue 2 (using @vue/composition-api
) and Vue 3.
Intro
Extend reactive object returned from composition function with additional reactive object(such as getters), or additional methods to get these benefits:
- Simplify api of object returned by a composition function.
- Eliminate overhead thinking of whether to use or not to use
value
property ofref
object to get its value.
Table of Contents
Installation
- Using NPM
npm install vue-extend-reactive
- Using Yarn
yarn add vue-extend-reactive
Usage
Hot Food! Temperature: {{ hotFood.temperatureInCelcius }} C Is it cool?: {{ hotFood.isCool ? 'Just cool. Into the mouth!' : 'Nope' }} Blow Again
API Reference
declare
Motivation
Both reactive and ref have quirk in terms of their syntax. Let's use hot food example above to show it.
Return reactive object returned as is
const coolTemperature = 22 { const state = { statetemperatureInCelcius -= 10 } // ... return state blow }
State would lost reactivity if destructured, so it have to be returned as is.
// Using reactive object named stateconst hotFood = hotfoodstatetemperatureInCelciushotfoodstateisHothotfood
Return refs
const coolTemperature = 22 { const temperatureInCelcius = const isHot =
Ref value have to be accessed through its value property. Ref may be unwrapped in template, but it causes syntax inconsistency, between template and script block.
// Using ref for each prop of stateconst hotFood = hotFoodtemperatureInCelciusvaluehotFoodisHotvaluehotFood// orconst temperatureInCelcius isHot blow = temperatureInCelciusvalueisHotvalue
Enter vue-extend-reactive
To achieve terser syntax, reactive object needs to be extended, maybe with another reactive object (like getters), or methods.
Reactive object can contain methods when using javascript, but make it more verbose to call it in same block, and create error when using typescript.
And thats why vue-extend-reactive
is created,
to enable reactive object extension leveraging Proxy object,
especially in typescript.
const coolTemperature = 22 { const state = { statetemperatureInCelcius -= 10 } // ... return }
Below is the end result after returning extended reactive object.
const hotFood = hotFoodtemperatureInCelciushotFoodisHothotFood
There is one caveat that returned reactive object cannot be destructured as it will lost reactivity, but that is a sacrifice I am willing to make, to get terser and more consistent syntax.