Kimkorng

Vue.js Tutorial For Beginners

31 JUL, 2024

Vue.js is a popular framework for building web applications. It's similar to other frameworks like React and Angular. This tutorial will help you understand Vue.js:

What is Vue.js?

Vue.js (pronounced "view") is a JavaScript framework for building user interfaces.

Setting Up Vue.js

Let's start by creating a simple HTML file named index.html.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learning Vue.js</title> </head> <body> <div id="app">{{ message }}</div> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <script> const app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }); </script> </body> </html>

This HTML file includes Vue.js using a CDN (Content Delivery Network). The app (Vue instance) links to the div with the id app and displays the message data property.

Vue.js Template Syntax

Vue.js uses a template syntax to bind the DOM (Document Object Model) to the data in your Vue instance.

Text Interpolation

You can display data in your HTML using double curly braces {{ }}.

html
<div>{{ message }}</div>

This code binds the message variable to the text content of the div.

Raw HTML

You can bind raw HTML content using the v-html directive.

html
<div v-html="rawHtml"></div>

Directives

Directives are special tokens in the Vue.js template syntax that provide reactive behavior to the DOM.

Attribute Bindings v-bind

Use v-bind to bind an attribute to an expression.

html
<template> <div> <img :src="imageSrc" alt="Dynamic Image"> </div> </template> <script> export default { data() { return { imageSrc: '/path/image.jpg' }; } }; </script>

You can also use the shorthand :.

html
<img :src="imageSrc">

If you don't use v-bind, the src attribute will be src="imageSrc" instead of src="/path/image.jpg".

Loops v-for

Use v-for to render a list of items from an array.

html
<div id="app"> <p>User List</p> <ul> <li v-for="user in users" :key="user.id">{{ user.name }}</li> </ul> </div> <script> const app = new Vue({ el: '#app', data: { users: [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }, { id: 3, name: Kimkorng Mao' } ] } }); </script>

Event Handling v-on

Use v-on to handle events like click, submit, etc.

html
<div id="app"> <p>{{ message }}</p> <button v-on:click="sayHello">Click me!</button> </div> <script> const app = new Vue({ el: '#app', data: { message: 'Hello!' }, methods: { sayHello() { this.message = 'Thanks for clicking!'; } } }); </script>

You can also use the shorthand @.

html
<button @click="sayHello">Click me!</button>

Conditional Rendering

Use v-if, v-else-if, and v-else to conditionally render elements.

html
<div v-if="isVisible">This is visible</div> <div v-else>This is hidden</div>

Two-Way Binding v-model

Use v-model to create a two-way binding on an input, textarea, or select element.

html
<input v-model="username">

Vue CLI

For larger projects, it's better to use Vue CLI, which helps you set up Vue projects easily.

Installing Vue CLI

Install Vue CLI globally using npm or yarn:

shell
npm install -g @vue/cli # or yarn global add @vue/cli

Creating a New Project

Create a new project using Vue CLI:

shell
vue create my-vue-app cd my-vue-app

Project Structure

Your project's structure will look like this:

plaintext
my-vue-app/ ├── node_modules/ ├── public/ │ ├── favicon.ico │ └── index.html ├── src/ │ ├── assets/ │ │ └── logo.png │ ├── components/ │ │ └── HelloWorld.vue │ ├── App.vue │ └── main.js ├── .gitignore ├── babel.config.js ├── package.json ├── README.md └── vue.config.js
  • node_modules/: Project dependencies.
  • public/: Static assets. index.html is the main HTML file.
  • src/: Source files.
    • assets/: Static assets like images.
    • components/: Vue components.
    • App.vue: Root component.
    • main.js: Entry point.
  • .gitignore: Files to ignore in version control.
  • babel.config.js: Babel configuration.
  • package.json: Project metadata and dependencies.
  • README.md: Project readme.
  • vue.config.js: Vue CLI configuration.

Running the Project

Start the development server:

shell
npm run serve

Visit http://localhost:8080/ to see your Vue app.

Understanding .vue Files

A .vue file has three main parts: template, script, and style.

Template

The template section contains the HTML structure of your component.

html
<template> <div class="user"> <h2>{{ name }}</h2> <p>{{ bio }}</p> </div> </template>

Script

The script section contains the JavaScript logic of your component. This includes data, methods, and props.

html
<script> export default { name: 'User', props: { name: String, bio: String } }; </script>

Style

The style section contains the CSS styles for your component. You can scope the styles to the component using the scoped attribute.

html
<style scoped> .user { margin: 20px; } </style>

Components & Props

Components are reusable elements in Vue. Here's how to create and use a User component.

Creating a User Component

Create a new file User.vue in the components folder.

html
<template> <div class="user"> <h2>{{ name }}</h2> <p>{{ bio }}</p> </div> </template> <script> export default { name: 'User', props: { name: String, bio: String } }; </script> <style scoped> .user { margin: 20px; } </style>

Using the User Component

In App.vue, import and use the User component.

html
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png" /> <User name="Kimkorng Mao" bio="The strongest man in the world" /> </div> </template> <script> import User from './components/User.vue'; export default { name: 'App', components: { User } }; </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; text-align: center; color: #2c3e50; margin-top: 60px; } </style>

Using Slots

Slots allow you to insert content into components.

Update User.vue component to use a slot.

html
<template> <div class="user"> <h2>{{ name }}</h2> <slot></slot> </div> </template>

Using Slots in App.vue

html
<template> <User name="Kimkorng Mao"> <p>The strongest man in the world!</p> </User> </template>

Vue.js Lifecycle Hooks

Vue.js provides a set of lifecycle hooks that allow you to run code at specific stages of a component's life. Here are some of the most commonly used hooks:

Example

html
<template> <div> <h1>{{ message }}</h1> <button @click="changeMessage">Change Message</button> </div> </template> <script> export default { data() { return { message: 'Hello, Vue.js!' }; }, methods: { changeMessage() { this.message = 'Message Changed!'; } }, beforeCreate() { console.log('beforeCreate'); }, created() { console.log('created'); }, beforeMount() { console.log('beforeMount'); }, mounted() { console.log('mounted'); }, beforeUpdate() { console.log('beforeUpdate'); }, updated() { console.log('updated'); }, beforeDestroy() { console.log('beforeDestroy'); }, destroyed() { console.log('destroyed'); } }; </script>
  1. beforeCreate: Called after the instance has been initialized, but before data observation and event/watcher setup.
  2. created: Called after the instance is created. At this stage, the instance has finished processing options, but the DOM has not been mounted yet.
  3. beforeMount: Called right before the mounting begins. The render function is about to be called for the first time.
  4. mounted: Called after the instance has been mounted. At this point, the el is replaced by the newly created vm.$el, and the mounted element is inserted into the DOM.
  5. beforeUpdate: Called when data changes, before the DOM is patched.
  6. updated: Called after data changes have caused the virtual DOM to be re-rendered and patched.
  7. beforeDestroy: Called right before a Vue instance is destroyed. At this stage, the instance is still fully functional.
  8. destroyed: Called after a Vue instance has been destroyed. When this hook is called, all directives, event listeners, and child Vue instances are removed.

What's Next?

Now that you have a basic understanding of Vue.js, here are some next steps to continue your learning journey:

  • Vue Router
  • State Management with Vuex
  • Vue 3 (Composition API, Teleport, and other new features)
SHARE