An example of a VueJS component code structure.

#vue
<!-- Component template -->
<!-- ------------------ -->
<template>
    <div class="component">

        <!-- Iterate through all items and display in the list -->
        <ul class="">
            <li v-for="item in items" :key="item.id">{{ item.title }}</li>
        </ul>

        <!-- Reference a child component with property and a click event calling a function -->
        <div class="childComponent">
            <Child-Component :childProperty="title" @clicked="doSometnig" class=""></Child-Component>
        </div>
        
        <!-- Display this title if the array of items is empty -->
        <h3 v-if="!items.length">Time to add new items!</h3>

    </div>
</template>

<!-- Define logic and data -->
<!-- --------------------- -->

<script>
// To use Child-Component you need to import it first
import Child-Component from './Child-Component';

export default {

    // If properties are being passed to this component from the parent you need to declare them here
    props: {
        propOne: {
            type: String, // String / Array / Number / Boolean
            required: true, // true / false
            default: ''
        }
    },

    // Declare all data for this component here
    data() {
        return {
            title: '',              // String
            count: 0,               // Number
            items: [],              // Array: []
            componentState: true    // Boolean: true / false
        }
    },

    // When the component if fully loaded run methods declared below
    mounted() {
        console.log(this.items);

        // Fetch data from an API using axios
        axios.get(`/api/items/`)
            .then(response => {
                this.items = response.data;
            })
            .catch(function (error) {
                console.log(error);            
            });
    },

    // Add methods
    methods: {
        doSometnig(){
            console.log(this.title);
        }
    },

    // Register loaded components
    components: {
        Child-Component // , Second-Component...
    }
}

</script>
copy

Create new Vue project in the current directory using Vue CLI command. To quickly create a project using default settings add "--default" flag at the end of the command.

#vue#cli
vue create project-name
copy

Directive "v-for" loops through an array and lets you output a new HTML element for each loop iteration.

#vue#loop#directive
<ul id="app">
    <li v-for="code in codes">{{ code }}</li>
</ul>

<script>
    new Vue({
        el: 'app',
        data: {
            codes: ['Javascript', 'HTML', 'CSS', 'PHP']
        }
    })
</script>
copy

Install Vue CLI as a global package.

#vue
npm install --global @vue/cli
copy

Mounted method lets you execute code once Vue is fully loaded and ready.

#vue
<script>
    new Vue({
        el: 'app',
        mounted() {
            console.log('Vue has mounted!')
        }
    })
</script>
copy

Create a new Vue instance.

#vue
<script>
    new Vue({
        el: "#app",
        data: {
            // Data object
        },
        methods: {
            // Methods object
        }
    });
</script>
copy

Serve Vue project using Vue CLI.

#vue#cli
npm run serve
copy

Example of toggling CSS class using v-bind, v-on:click and inline conditional statement.

#vue#class
<div id="app">
    <button v-bind:class="{ 'toggled' : is_active }" v-on:click="toggle_class()">Toggle</button>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            is_active: false
        },
        methods: {
            toggle_class(){
                return this.is_active ? this.is_active = false : this.is_active = true
            }
        }
    })
</script>
copy

Use "v-bind:" or a ":" shorthand for a two-way data binding with the selected attribute.

#vue#directive
<a v-bind:href="yourHref" v-bind:title="yourTitle" v-bind:class="yourClass"> {{ yourLink  }}</a>
<!-- Using shorthand -->
<a :href="yourHref" :title="yourTitle" :class="yourClass"> {{ yourLink  }}</a> 

<script>
    new Vue({
        el: '#app',
        data: {
            yourHref: '/home',
            yourTitle: 'Homepage',
            yourClass: 'link',
            yourLink: 'Back to home'
        }
    })
</script>
copy

v-model binding is a directive designed to work with forms and input fields.

#vue#directive
<div id="app">
    <input type="text" v-model="hello">
    <p>{{ hello }}</p>
</div>

<script>
    new Vue({
        el: 'app',
        data: {
            hello: 'Good day!'
        }
    })
</script>
copy

Vue on click directive listens for a click event on a given element. You can reference a method to fire on each click. Use v-on:click or a shorthand @click, they work exactly the same way.

#vue#on#event
<input v-model="newRecord" type="text">
<button v-on:click="addRecord">Add record</button>

<script>
    new Vue({
        el: '#app',
        data: {
            newRecord: '',
            records: []
        },
        methods: {
            addRecord(){
                this.records.push(this.newRecord);
                this.newRecord = "";
            }
        }
    })
</script>
copy

Show this element as long as the value is true.

#vue#directive
<div id="app">
    <button v-show="guest">Login</button>
</div>

<script>
    new Vue({
        el: 'app',
        data: {
            guest: true
        }
    })
</script>
copy
NordVPN NordVPN