Useful getting started guide in Vue js

Vue js is a Javascript framework for building user interfaces. It builds on top of standard HTML, CSS, and Javascript, so it is better to know them before diving into Vue js.

What you need to know

Declarative rendering

Declarative rendering is using the template syntax that extends the HTML. You describe how an HTML should look based on the Javascript state. For example.

<script>
  export default {
    data() {
     return {
       message: "Hello from Vue js"
   }
 }
}
</script>

<template>
<h1>{{message}}</h1>
</template>

From the above, it will bring Hello from Vue js, its because the message property is made available from the template.

Binding in Vue js

Data binding in Vue means that the place where Vue is used or displayed in the template is directly linked or bound to the source of the data which is the data object inside the Vue instance.

We use v-bind to bind n attribute to dynamic value. Example

<h1 v-bind:id="dynamicId"></h1>

You can also use the shorthand version because we use this frequently.

<h1 :id="dynamicId"></h1>

Example in code

<script>
export default {
  data() {
    return {
      myMessage: 'auto'
    }
  }
}
</script>

<template>
  <h1 :class="myMessage">Auto garage</h1>
</template>

<style>
.auto {
  color: green;
}
</style>

The output from the above is Auto garage with green letters

Vue Event Listeners

To listen to dom events in Vue, we use v-on, event listener is a procedure that waits for an event to occur before being triggered.

<button v-on:click="increment">{{number}}</button>

Also, you can do a shorthand version of this with the following:

<button @click="increment">{{number}}</button>

To access a component inside a method function, use the this keyword.

Working with Forms

Use v-bind and v-on together to create a two-way binding on form input.

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

Sometimes the above becomes too much work to write. To simplify we use the v-model.

<input v-model="text">

Conditional Inheritance

When we want to write conditions in Vue we us v-if to conditionally render an element. You only render when the condition is true, when it’s false the value is removed from the dom.

<h1 v-if="like">I like playing</h1>

For an else and else if statement we use v-else and v-else-if respectively.

List Rendering

To list items in an array, use v-for like the example below.

<li v-for="todo in todos":key="todo.id">{{todo.message}}</li>

If you want to add a new item to the array use push keyword, for example this.todos.push(<array>)

About Mason Kipward

I am a technology enthusiast who loves to share gained knowledge through offering daily tips as a way of empowering others. I am fan of Linux and all other things open source.
View all posts by Mason Kipward →

Leave a Reply

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