The easiest counter ever!
(or the simplest way to get a reactive frontend app running)
Setting up a web app can be a tedious task, but there's a way to get up and running instantly.
Enter Pug and Petite-Vue !
All we need is to create a Pug (.pug) file.
// index.pug
// Import petite-vue
script(src="https://unpkg.com/petite-vue" defer init)
// Create a scoped state for petite-vue to work
div(v-scope="{ count: 0 }")
// Display the count
span.
{{count}}
// Add a button to increment the count
button(@click="count++") Increment
Now you can just run npx parcel index.pug
to start a dev server using parcel (node must be installed).
And voilà!
A more in depth analysis
Why defer
and init
The defer
keyword tells the browser to wait until every HTML element is loaded before executing the script.
init
is a petite-vue
specific keyword which means that the vue script will be run as soon as possible (without waiting to be started manually)
The v-scope
The v-scope
is the place where we define the local state. For the counter we defined a count
property that is available to the element's children.
What's up with this weird .
?
When using pug, we can't use the usual syntax:
// This is not valid
span {{count}}
// This is not valid either
span
{{count}}
Pug won't understand why there are curly braces and will throw an error.
A workaround could be to write
span(v-text="count")
but that's a little too verbose 😈.
So I choose to use a small Pug feature, the dot. Putting a dot at the end of a line means the children will be rendered as plain text, and that's exactly what we need.
span.
{{count}}
Here is the full code snippet without comments.
script(src="https://unpkg.com/petite-vue" defer init)
div(v-scope="{ count: 0 }")
span.
{{count}}
button(@click="count++") Increment
Thanks for reading!