Vue's Reactivity By Example

We wanted to create a landing page for our association; kolmekolmesata, so I created one.
You might like the site if you enjoy seeing bunch of SVG polygons appear and disappear over and over again, but you might not like it if you’re after information about our association, well you can’t please them all.
In this brief post I’ll explain what I learned during the process.

The site was created with Vue.js using SVG, in this post I’ll briefly explain how the Vue’s reactivity system makes it so easy to declare a view like this:

<template v-for="x in xAmnt">
<template v-for="y in yAmnt">
<cube
:height="cubeHeight"
:width="cubeWidth"
:x="getXCoord(x, y, cubeWidth, cubeHeight)"
:y="getYCoord(x, y, cubeWidth, cubeHeight)"
:toggled="isToggled(x, y)"
:key="x + y * xAmnt"
@mouseover.native="mouseOverCube"
/>
</template>
</template>

and as a result see something like this:

animated cubes

How it works; so the template above declaratively defines the entire view. The value isToggled returns for each coordinate varies over time. So one might wonder how does Vue track the properties used in .isToggled()?

Well Vue’s documentation does no exceptions here, it is very good also on this subject.
The gist is that during the initializing of your component, Vue walks through your data object and defines getters and setters for each property.
Each component has a watcher, the watcher defines whether a property’s getter has been run during the execution of the template (or render method), if so the property is marked as “touched”. The watcher is also used when a setter is called for the touched property, the watcher then re-trigger the rendering of the component.

So in our case on the first render Vue notices that rendering these cubes uses a distanceToSweetSpot property, as every cube’s coordinate is compared to it.
In our app this distance is changed simply by assigning a new value to it every interval. Vue has defined the setter for the distanceToSweetSpot property with Object.defineProperty, the setter is executed every interval. When executing the setter it notifies the watcher that we’d want to re-trigger the templating function.

If you’re interested on the details of the site, feel free to read the source from the repository in github.

← Home