Categories
Vue

Vue: the missing manual

Vue offers the “ref” function to wrap variables:

const message = ref('I am a variable')

You can reach the value of that variable via .value

message.value

Another way to access state is via directives. Example here:

<h1 v-bind:class="dynamicClassHere"></h1>

And in your script section:

const dynamicClassHere = ref('blue')

<style> .blue { color: blue } </style>

When the “dynamicClassHere” variable change, that is bind to the element, and it gets updated.

The above can also be short cutter to:

<h1 :class="dynamicClassHere"></h1>

Event listeners

<button @click="increment">Count is {{ count }}</button>

function increment() { count.value ++ }

Form binding

<input :value="text" @input="onInput">

function onInput(e) { // do something here };

You can accomplish the same using the v-model directive:

<input v-model="text">

Basically, the above skips the need of an “onInput” function

Conditional rendering

This is done via the v-if and v-else directive:

<h1 v-if="conditionalVar">Yay!</h1>

<h1 v-else>Nope</h1>

In this case, the one or the other H1 will show, depending on the boolean conditionalVar

Leave a Reply

Your email address will not be published. Required fields are marked *