Home Vue.js Cheatsheet [Under Development]
Post

Vue.js Cheatsheet [Under Development]

This post is intended to be a quick reference - Cheatsheet of VueJS functionality.
This post is not meant to replace a proper course, tutorial, or event documentation. But rather, to supplement it with some code examples and a quick reference to useful functionality and patterns.

The original Vue documentation can be found here.

What is Vue JS

Vue.js is a javascript frontend framework which can be used to develop single page applications.

New Project

The following are common commands to setup and work with a new vue project.

1
2
3
4
5
npm init vue@latest
cd #Project Name - Change directory to your newly created project
npm install #install dependencies
npm run dev #test the project on localhost
npm run build #build the final website

Alternatively, simply include vue in your index html file.

1
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

Vue App

Vue can take partial control of a page. Vue js can control a simple div for example in the whole page. Here’s how to do it. There can be multiple Vue Apps in a page.
The controlled element is a template.

1
2
3
4
5
<div id="Foo"></div>

<script>
Vue.CreateApp({ ... }).Mount("#Foo")
</script>

“#Foo” is a modern js css selector. It selects the dom element with id Foo.

Interpolation

The weird ”“ syntax, which can be used when vue takes control of a dom element, is called interpolation. It can be used to define placeholders for actual data, as is shown below.

1
2
3
4
5
<div id="btn">
    <!-- This '' syntax is called interpolation,
    ButtonTitle is a placeholder here for reactive data -->
  <button></button> 
</div>
1
2
3
4
5
6
7
8
9
10
const app = createApp({
  //data is one of multiple, built in options
  data() { //Data used for interpolation
    return { //always returns a js object
      ButtonTitle: "Click me"
    }
  }
})

app.mount("btn")

Interpolation can also be used to execute standard JS expressions.

1
2
3
<div id="btn">
  <button>1</button> 
</div>

v-bind Vue Directive

v-bind is a very common built-in directive, which among other things, can bind a DOM Element’s attribute name to a backing data value. This is called data binding.

Example:

1
2
3
<p id="vctrl">
    <a v-bind:href="URL">This is a link</a>
</p>
1
2
3
4
5
6
7
const app = createApp({
  data() { 
    return {
      URL: "http://www.somedomain.com"
    }
  }
}).mount('vctrl')

Since v-bind is very common, there’s a shortcut usage, simply ”:”

1
2
3
<p id="vctrl">
    <a :href="URL">This is a link</a>
</p>

methods option

Methods is another vue option, like data, which defines, well, methods.

1
2
3
4
5
6
7
const app = createApp({
  data() { ... },
  methods : {
    MethodOne : function(){ ... }, //Property name: MethodOne, Property Value: a function
    MethodTwo() {} //Modern JS, equivalent syntax to the one above
  }
})

The this keyword

“this” is a standard js keyword, but it has a special functionality in Vue.

1
2
3
4
5
6
7
8
9
10
11
12
const app = createApp({
    data() {    
        return {
            Hello: "Hello Vue!"
        }
    },
    methods : {
        HelloMethod : function(){ 
            return this.Hello;
        }
    }
})

It is used to access internally defined data.

The v-on Vue directive

The v-on vue directive is used to define event listeners for DOM elements, like click, input, dragover etc…

1
<button v-on:click="TestButtonClick">Test Button</button>

or

1
<button v-on:click="TestButtonClick()">Test Button</button>

or even (Simple js expressions are also valid)

1
<button v-on:click="alert('Clicked Test Button')">Test Button</button>
1
2
3
4
5
6
7
const app = createApp({
    methods : {
        TestButtonClick : function(){ 
            alert("Clicked Test Button!");
        }
    }
})

We can also call v-on with parameters:

1
<button v-on:click="SomeMethod(10)">Test Button</button>

This would call the backing method SomeMethod with a number parameter 10.

v-on is a common vue directive, and its shortcut is @, eg. @click=…

v-on event modifiers

Details of different event modifiers can be found here.

For example the prevent modifier, disables the default redirection of a form.

1
2
3
<form @submit.prevent="MyMethod($event)">
    <button>Submit</button>
</form>

The v-model vue directive

v-model can be used on a component to implement a two-way binding.

On input element for example:

1
<input type="text" v-model="SomeDataName">

This makes input update its text when the SomeDataName value changes from code-behind, and it also updates the SomeDataName as the user interacts with it.

The computed option

Computed is yet another vue option.

1
<p>  </p>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const app = createApp({
    data() {    
        return {
            Prefix: "Hello",
            Suffix: "Vue!"
        }
    },
    methods : { ... },
    computed : {
        WholeWord : function(){
            return this.Prefix + " " + this.Suffix;
        }
    }
})

A computed method tracks all changes to the data the method uses, its’ dependencies, and only fires the method when a change occurs.

So, only when the Prefix or Suffix value change, does the WholeWord method execute. This is good for performance.

Note that the WholeWord is used like a property, not a method, inside the html tag.

The watch option

The watch option is another valid vue option, like data or methods. It’s purpose is to define methods that execute whenever the “watched” property changes.

1
2
3
4
5
6
7
8
9
10
11
12
const app = createApp({
    data() {    
        return {
            hello: "Hello"
        }
    },
    watch : {
        hello(newvalue, previousvalue){
            alert(`The old value of hello is ${previousvalue} - the new one is ${newvalue}`);
        }
    }
})

The watch method should have the same name as the property or data it “watches”, and 0, 1, or 2 arguments. If only one argument is defined, that would be the latest value of hello.

Dynamic Styling

In vue, we can add css classes to html DOM elements dynamically, depending on a true/false condition.

Example:

1
2
3
4
5
6
7
.red-css-class{
    background-color : red;
}

.foreground{
    color: green;
}
1
<div class="foreground" :class="{red-css-class : isRed}"></div>
1
2
3
4
5
6
7
const app = createApp({
    data() {
        return {
            isRed: true
        }
    },
})

In the above example, the red-css-class css class is added to the div, if the data value of isRed is true. Make sure to always use true/false data values when using this pattern. We can also define all non-dynamic classes in a separate class attribute.

Dynamic Styling and computed properties

It is also possible to use computed properties to achieve the above functionality.

1
2
3
.red-css-class{
    background-color : red;
}
1
<div :class="IsRedActive"></div>
1
2
3
4
5
6
7
8
9
10
11
12
const app = createApp({
    data() {
        return {
            isRed: true
        }
    },
    computed : {
        IsRedActive : function(){
            return { red-css-class : isRed };
        }
    }
})

The computed property IsRedActive is recalculated whenever the isRed property is altered, and it returns the appropriate object to be used by the dynamic and bound css class.

Conditional Rendering

We can use the v-if directive to conditionally render an element in our html code. There’s also the v-else-if and v-else directive.
v-else-if and v-else has to be used directly below an element with the v-if or v-else-if directive.

1
2
3
<div v-if="expression"></div>
<div v-else-if="expression"></div>
<div v-else></div>

v-show

Another directive similar to v-if, is the v-show. The v-if directive completelly adds or removes elements in the dom tree, whereas the v-show directive hides/shows them.

The v-for directive

The v-for directive helps us show repeated content based on a bound list of js objects.

It’s vital to generate a unique key for each element.

1
2
3
<ul>
    <li v-for="item in items" :key="Math.random()"></li>
</ul>
1
2
3
4
5
6
7
const app = createApp({
    data() {
        return {
            items: [ "item 1", "item 2", "item 3"];
        }
    }
})

v-for provides access to its object, (item in our example) only within the bounds of the enclosing html tag (li in our example).
v-for also supports getting an element’s index in the containing list.

1
2
3
<ul>
    <li v-for="(item, index) in items"> : </li>
</ul>

The ref attribute

Sometimes, we need access to an html dom element. The ref can be used to provide access to said dom element, in vue.

1
<div ref="SomeInput"></div>
1
var divElem = this.$refs.SomeInput;

Component

Vue components should be defined in their own .vue files. A component is comprised of 3 main parts:

  • script
  • template
  • style
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
export default {
  data() {
    return {
      //etc...
    };
  }
//etc...
};
</script>

<template>
<div>
    ...
</div>
</template>

<style scoped>
    ...
</style>

Importing a component in another vue component is done with js import.

1
2
3
4
5
6
7
8
9
10
11
<script>
import { ComponentName } from './components/ComponentName.vue'

export default {
    data() { ... },
    methods : { ... },
    components: {
        ComponentName
    }
};
</script>

Props

props can be used to export a default array of properties in a vue component.

1
<CustomComponent my-prop="somedata"></CustomComponent>
1
2
3
4
export default{
    props: ['myProp'],
    //...
}

Props should use CamelCase notation in js, and dash between words notation in html. Vue automatically converts between the two.
Props are unidirectional, which means only the parent can pass data to a child component prop. The child component cannot alter the props’ values.

Props can also accept an object if you need to define more constraints.

1
2
3
4
5
6
7
8
9
10
export default{
    props:{
        myProp : {
            type : String,
            required: false,
            default : "DefaultValue",
            validator(value){ ... }
        }
    }
}

$emit

emit is a built in vue method, just like refs. I can be used to emit an event from the component to the parent. For example when a model property changes.

1
2
3
4
5
6
7
8
export default{
    methods : {
        myMethod(){
            this.$emit("my-event");
        }
    }
}

This post is licensed under CC BY 4.0 by the author.