Your first component
Build a user card from your own markup, mount it twice, and change one card's data. It takes about five minutes, and it uses Component, the module most vUX apps are built on.
1. Write the template
A component is defined by markup you write. Mark the places that show data with data-v-* attributes, each naming a field:
<script type="module" src="main.js" data-id="vUX" data-library-root="/lib/vUX/"></script>
<template id="userCard">
<article class="card" data-v-class="muted:away">
<h3 data-v-field="name"></h3>
<p data-v-field="role"></p>
<button data-v-on="click:greet">Say hello</button>
</article>
</template>
<div id="people"></div>| Attribute | Does |
|---|---|
data-v-field="name" | Sets the element's text from the name field. |
data-v-class="muted:away" | Adds the class muted while the away field is true. |
data-v-on="click:greet" | Calls the greet handler on click. |
Every binding names a field, never an expression. Anything computed goes in JavaScript.
2. Create the component
import { Component } from "/lib/vUX/vUX-component.js";
const card = new Component($$.ss("#userCard"));
card.config.handlers = {
// handlers get the instance's current data
greet: (data) => alert("Hello, " + data.name)
};
card.initialize();The constructor takes the element itself, not a selector string. $$.ss() is the core's querySelector, available once any vUX module has loaded.
3. Mount instances
mount() clones the template into a container with the data you give it, and returns an instance:
const people = $$.ss("#people");
const ada = card.mount(people, { name: "Ada Lovelace", role: "Analyst", away: false });
const alan = card.mount(people, { name: "Alan Turing", role: "Theory", away: true });Two cards appear. Alan's carries the muted class.
4. Change the data
update() merges the fields you pass and writes only the bindings whose value changed. It returns the names of the fields that moved:
ada.update({ role: "Lead analyst" }); // ["role"]
ada.update({ role: "Lead analyst" }); // [] - same value, nothing written
alan.update({ away: false }); // ["away"]: the class comes off5. Tear it down
alan.destroy(); // one instance: listeners released, node removed
card.destroyAll(); // every instance this component madeWhat next
- Lists that keep their nodes through a sort: keyed lists with
sync(). - Data several components show at once: Build a cart with shared state.
- Every option: the Component reference.