VueJS Tutorial For Beginners

VueJs Tutorial from Codingcompiler. Here in this Vue tutorial we discuss most of the basic functions of the Vue core. Let’s start learning Vue JavaScript.

What is Vue.js?

Vue.js is a set of progressive frameworks for building user interfaces . Unlike other heavyweight frameworks, Vue is fundamentally based on a minimally cost, incrementally adoptable design. Vue’s core library focuses only on the view layer and is easy to integrate with other third-party libraries or existing projects. On the other hand, when used in conjunction with single file components and libraries supported by the Vue ecosystem , Vue is also fully capable of providing powerful drivers for complex single-page applications.

Let’s Start with Vue.js Tutorial

The official guide presupposes that you already have intermediate levels of knowledge in HTML, CSS, and JavaScript. If you are just starting to learn front-end development, skip the basics and use the framework as your starting point may not be the best idea – master the basics again! Previous experience with other frameworks will help you learn Vue.js, but it is not required.

The easiest way to try Vue.js is to use the JSFiddle Hello World example . You can open it in a new tab in your browser and follow the basic examples to learn some basic usage. Or you can locally create a index.html file, and then introduced Vue by:

<!-- Development version with useful console warnings -->
< script src = "https://cdn.jsdelivr.net/npm/vue/dist/vue.js" ></ script >
or:
<!-- Generate version, optimize for size and speed -->
< script src = "https://cdn.jsdelivr.net/npm/vue" ></ script >

Check out the installation page for additional options for installing Vue. Note: We do not recommend novice from vue-cli the beginning of the project, especially when you are not familiar with Node.js based build tool.

If you prefer to be interactive, check out the Scrimba series of tutorials , which provide you with screen recording and code test sites, and can be paused and played at any time.

VueJS Declarative Rendering

Learn this lesson in Scrimba

At the heart of Vue.js is the ability to declaratively render data to DOM using a clean template syntax:

 < div id = "app" >
 {{ message }}
</ div >
Var app = new Vue({
el: '#app' ,
data: {
  message: 'Hello Vue!'
 }
})
Hello Vue!

We have generated the first Vue app! This looks very similar to rendering a string template, but Vue does a lot of work behind it. Now that data and DOM are already linked, all data and DOM are responsive . How do we clearly understand this? Open your browser’s JavaScript console (now, in the current page open), and then set app.message the value, you will see the above example the rendered DOM element is updated accordingly.

[Related Article: JavaScript Animation Libraries ]

In addition to text interpolation, we can also bind DOM element attributes in this way:

< div id = "app-2" > 
< span v-bind:title = "message" >     
Hover over here for a few seconds,you can see the title dynamically bound here!
</ span > </ div >

Var app2 = new Vue({
el: '#app-2' ,
data: {
  message: 'page loaded in ' + new Date ().toLocaleString()
}
})

Hover over here for a few seconds, you can see the title dynamically bound here!

Here we have encountered some new content. You see the v-bindproperty is called command . Instructions are prefixed v-to indicate that they are private properties provided by Vue. As you may have guessed, they produce specialized responsive behavior on the rendered DOM. Briefly, the effect of this instruction is: “this element title attributes Vue instance message attributes remain associated update.”

If you open your browser’s JavaScript console again and enter app2.message = ‘Some new message‘, you will see again, bound title attributes HTML has been updated.

[Related Article: Babel Presets]

VueJs Condition and Cycle

Learn this lesson in Scrimba

Controlling the display of an element is also simple:

< div id = "app-3" > 
< span v-if = "seen" > Now you can see me </ span >
</ div >

Var app3 = new Vue({
el: '#app-3' ,
data: {
  seen: true
 }
})

Now you can see me

Continue typing in the console app3.seen = false and you should see the span disappear.

This example shows that we can not just bind data to text and properties, but also bind data to a DOM structure . Moreover, Vue also provides a powerful transition effects system that automatically uses transition effects when Vue inserts/updates/deletes elements .

[Related Article: JavaScript Design Patterns ]

There are other instructions, each with its own special function. For example, an v-for instruction can use a data in an array to present a list of items:

< div id = "app-4" > 
< ol >
< li v-for = "todo in todos" > {{ todo.text }} </ li >
</ ol >
</ div >

Var app4 = new Vue({
el: '#app-4' ,
data: {
  todos: [
    { text : 'learn JavaScript' },
    { text : 'learn Vue' },
    { text : 'create exciting code' }
  ]
}
})
  1. Learning JavaScript
  2. Learning Vue
  3. Create exciting code

In the console, type app4.todos.push({ text: ‘New item’ }), you will see a new item added to the list.

Handling User Input in VueJs

Learn this lesson in Scrimba

To give your users and applications to interact, we can use the v-on command to add event listener method as defined under Vue instance methods will be called after the trigger event:

< div id = "app-5" > 
< p > {{ message }} </ p >
< button v-on:click = "reverseMessage" > flip message </ button >
</ div >


Var app5 = new Vue({
el: '#app-5' ,
data: {
  message: 'Hello Vue.js!'
 },
methods: {
  reverseMessage: function () { this .message = this .message.split( '' ).reverse().join( '' )    } } })


Hello Vue.js!

Flip message

Note that, in the reverseMessage process, we’ve updated the status of the application, without having to touch DOM – all DOM operations handled by the Vue, the code you write just need to focus on the underlying logic.

Vue also provides v-model instructions such that binding between the two-way form input and application state breeze:

< div id = "app-6" > 
< p > {{ message }} </ p >
< input v-model = "message" >
</ div >

Var app6 = new Vue({
el: '#app-6' ,
data: {
  message: 'Hello Vue!'
 }
})
Hello Vue!

An Vue Application Composed of Components

Learn this lesson in Scrimba

Component systems are another important concept of Vue because it is an abstraction that allows us to build large applications using small, self-contained, and often reusable components. Think about it, almost any type of application interface can be abstracted into a component tree:

In Vue, a component is essentially a Vue instance with predefined options, and registering components in Vue is simple:

 // Define a new component
named 'todo-item' Vue.component( 'todo-item' , {
template: '<li>this is a todo item</li>'
})

Now you can combine it in another component template:

 < ol > <!-- Create an instance of the todo-item component --> < todo-item > </ todo-item > </ ol > 

But this will make each todo item render the same text, which doesn’t look cool. We should pass data from the parent scope to the child component. Let’s modify the definition of the next component so that it can accept a prop :

Vue.component( 'todo-item' , { // The todo-item component now accepts a "prop", // similar to a custom property. // This prop is called todo.   props: [ 'todo' ],  template : '<li>{{ todo.text }}</li>' })

Now, we can use the v-bind instruction todo each incoming duplicate components:

 < div id = "app-7" > < ol > <!--      Now we provide a todo object for each todo-item      whose content is dynamic.      We also need to provide a "key" for each component,      which will be explained in detail later.    --> < todo-item v-for = "item in groceryList" v-bind:todo = "item" v-bind:key = "item.id" > </ todo-item > </ ol > </ div >  
 Vue.component( 'todo-item' , {
props: [ 'todo' ],
template: '<li>{{ todo.text }}</li>'
})

Var app7 = new Vue({
el: '#app-7' ,
data: {
  groceryList: [
    { id : 0 , text : 'vegetable' },
    { id : 1 , text : 'cheese' },
    { id : 2 , text : 'Other human food' }
  ]
}
})
  • vegetables
  • cheese
  • Other human food

This is a hypothetical example, however, we have tried to divide the application into two smaller units, and the subcomponents form a fairly reasonable decoupling from the parent component through the props interface. We can now further <todo-item> components more complex configuration templates and improved terms of logic, without affecting the parent component.

[Related Article: Basics of Functional Programming]

In a large application, it is necessary to divide the entire application into components so that management can be maintained during development. We’ll dive into the components in a later component guide , but here’s an example of a template for an (imaginary) application that uses components:

< div id = "app" > < app-nav > </ app-nav > < app-view > < app-sidebar > </ app-sidebar > < app-content > </ app-content > </ app- View > </ div >

Relationship with custom elements in Vue

As you may have noticed, the Vue component is very similar to the Custom Element in the Web component specification . This is because Vue’s component syntax follows the specification without any restrictions. Vue assembly realized e.g. Slot API and special attributes. However, there are still some key differences:is

  1. The Web component specification is still in the draft phase and has not been natively implemented by the browser. In contrast, Vue components do not require any polyfill patching and behave consistently across all supported browsers (IE9 and above). Vue components can also be included in the native custom element specification if necessary.
  2. Vue components provide some important features that are not available with common custom elements, most notably cross-component data flow, custom event communication, and build tool integration.

We have just briefly introduced the most basic functions of the Vue core.

[Related Article: Top 10 Programming Languages ]

Vue Instance

How to create a Vue instance?

Each Vue applications are through Vue to create a new function Vue instance begins:

Var vm = new Vue({ // option })

Although the MVVM model is not fully followed , Vue’s design is still inspired by it. As a convention, we usually use variables vm (short for ViewModel) to represent Vue instances.

When you create a Vue instance, you pass in an options object. Most of this guide describes how to use options to achieve the desired behavior. A complete list of options can be browsed in the API reference documentation.

[Related Article: Kubernetes API Tutorial ]

“Use a Vue application by the new Vue creation of a root instance Vue “, “nested tree structure (optional)” and “reusable components” components. For example, the component tree for a todo application might look like this:

Root Instance
└─ TodoList
├─  TodoItem  
│ ├─ DeleteTodoButton  
│ └─  EditTodoButton     
└─     TodoListFooter
├─ ClearTodosButton
└─ TodoListStatistics

Later, we will detail the component system . For now, all you need to know is that all Vue components are Vue instances, and the components all receive the same option object (except for some root-specific options).

Data and Methods in Vue

When you create Vue instance, will all data the properties found objects, are added to the Vue response systems in. Whenever the value of these properties changes, the view responds “in time” and updates the corresponding new value.

// data object
var data = { a : 1 }

// This object will be added to the Vue instance
var vm = new Vue({
data: data
})

// Get the property on the instance
// will return the property in the original data
vm.a == data.a // => true

// Set the properties on the instance,
// will also affect the original data
vm.a = 2
data.a // => 2

// ... and vice versa
data.a = 3
vm.a // => 3

View re-rendering whenever the data object changes. It is noteworthy that, if the instance has been created, then only those data in the already existing properties, is responsive in. That is, if after the instance is created, add a new property, for example:

Vm.b = 'hi'

Then, change b will not trigger any view updates. If you know in advance, you will use an attribute that starts empty or does not exist. You need to set some initial values ​​in advance. E.g:

Data: {
newTodoText: '' ,
visitCount: 0 ,
hideCompletedTodos: false ,
todos: [],
error: null
}

The only exception here is use Object.freeze() to prevent an existing property is modified, it also means responsive system can not track _ _ change.

Var obj = {
foo: 'bar'
}
Object .freeze(obj)
New Vue({
el: '#app' ,
data: obj
})

< div id = "app" >
< p > {{ foo }} </ p > <!-- This will no longer update `foo`! -->
< button v-on:click = "foo = 'baz' " > Click me to modify </ button > </ div >

In addition to the data property, Vue instances expose some useful instance properties and methods. These properties and methods are prefixed $to distinguish them from user-defined properties. E.g:

Var data = { a : 1 }
var vm = new Vue({
el: '#example' ,
data: data
})

Vm.$data === data // => true
vm.$el === document .getElementById( 'example' ) // => true

// $watch is an instance method
vm.$watch( 'a' , function ( newValue, oldValue ) { // This callback function will be called after `vm.a` is changed })

Later, you can consult the API reference documentation for a complete list of instance properties and methods.

Vue Instance Lifecycle Hook Function

Each Vue instance goes through a series of initialization processes before it is created – for example, Vue instances need to set up data observation, compile the template, mount the instance in the DOM (mount the instance) To the DOM), and update the DOM when data change. During this process, the Vue instance also calls some lifecycle hook functions so that users can add their own code at a particular stage.

[Related Article: UX Trends 2019 ]

For example, after calling instance created created hook function:

 New Vue({
data: {
  a: 1
 },
created: function () { // `this` points to the vm instance console.log( 'a is: ' + this .a)  } }) // => "a is: 1"

There are also other hooks that are called at different stages of the instance lifecycle, such as mounted, updated and destroyed. All hook function when invoked, its this context will point to call it Vue instance.

[Related Article:  Python Standard]

Note: Do not use arrow functions (for example, created: () => console.log(this.a)or vm.$watch(‘a’, newValue => this.myMethod())) in option properties or callback functions . Because arrow binding function of the parent context, it thisdoes not point as expected Vue example, often produce false positives, e.g. Uncaught TypeError: Cannot read property of undefined, or Uncaught TypeError: this.myMethod is not a function.

Vue Life Cycle Diagram

The following is a schematic diagram of the life cycle of an instance. You don’t need to understand everything right now, but this diagram will be a helpful reference when you delve into learning and organizing the architecture.

Vue Template Syntax

Vue.js uses HTML-based template syntax that allows for declarative binding of data data in DOM and Vue instances to be rendered. All Vue.js templates are valid HTML and can be parsed by a standard browser and HTML parser.

On the underlying implementation, Vue compiles the template into a render function that can generate a Virtual DOM. Combined with a responsive system, Vue intelligently finds the minimum number of components to re-render and applies the least amount of DOM operations as the application state changes.

[Related Article: VirtualBox Interview Questions]

If you are familiar with the concept of virtual DOM and prefer to use native JavaScript, you can instead write a render function without the use of templates , with optional JSX syntax support.

You can also perform one-time interpolation by using the v-once command , which means that the interpolated content will not be updated as the data changes. But keep in mind that this will also affect all other bindings on the same node:

< span v-once > The value here never changes: {{ msg }} </ span >

Original HTML (Raw HTML)

The double brace syntax converts the HTML in the data to plain text before interpolating. In order to output true HTML, you need to use the v-htmlcommand:

< p > Use double curly brace syntax: {{ rawHtml }} </ p >
< p > Use the v-html directive: < span v-html = "rawHtml" > </ span > </ p>

Use double curly braces syntax: <span style=”color: red”>This should be red.</span>

Use the v-html directive: This should be red.

Span Contents, will be replaced by the rawHtml value of the attribute, and insertion as the original HTML – ignores the parsed data attribute values binding. Please note that can’t be used v-html to combine partial template, because the Vue is not based on a string (string-based) template engine. Conversely, for the user interface (UI), components are better suited as a basic unit of reusability and combinability.

Notes: Dynamic rendering of arbitrary HTML on a website is very dangerous because it can easily lead to XSS attacks on websites . Please use HTML interpolation only for trusted content, and never use HTML interpolation for user-provided content.

[Related Article: SQL Server DBA Tutorial ]

Vue Attributes

You cannot use double brace syntax (mustache) on HTML attributes in a Vue template. Instead, you should use the v-bind directive :

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

In some cases where the attribute is a Boolean type, v-bind the effect is a bit different, as long as the value exists, it is implicit true. In this example:

<button v-bind:disabled="isButtonDisabled">Button</button>

If the isButtonDisabled values null, undefined or false, disabled property even not be included in the rendered <button> elements.

[Related Article: SQL Getting Started Guide]

Use a JavaScript expression in Vue

So far, we have only implemented binding the template to the basic property key. However, Vue.js actually supports binding a template to arbitrary data through a full JavaScript expression:

{{ number + 1 }}{{ ok ? ‘YES’ : ‘NO’ }}{{ message.split(”).reverse().join(”) }}<div v-bind:id=”‘list-‘ + id”></div>

These expressions will be taken as JavaScript values ​​under the data scope of the Vue instance to which they belong. There is a restriction that each binding can only contain a single expression , so the following examples will not work :

<!– This is a statement, not an expression –>{{ var a = 1 }}<!– Flow control also does not work, please use ternary expression –>{{ if (ok) { return message } }}

Note: Template expressions are placed in a sandbox can only access the global variables of a white list, such as Math and Date. In template expressions, you should not attempt to access user-defined global variables.

[Related Article: Amazon Redshift]

Vue Directives

Directives are special attributes with the v- prefix. Directive attribute values are expected to be a single JavaScript expression (with the exception for v-for, which will be discussed later). A directive’s job is to reactively apply side effects to the DOM when the value of its expression changes. Let’s review the example we saw in the introduction:

<p v-if="seen">Now you see me</p>

Here, v-if the instruction according to the expression seen to remove / insert the truth value of <p> the element.

[Related Article: 50 Best Free Modern Fonts Download]

Vue Parameters (Arguments)

Some instructions capable of receiving a “parameter“, after the instruction name: indicates. For example, a v-bind instruction can be used to responsively update an HTML attribute:

<a v-bind:href=”url”> … </a>

Here href is a parameter informing v-bind instruction element href attributes expression url bound value.

Another example is the v-oncommand, DOM events for listeners:

<a v-on:click="doSomething"> ... </a>

Here, the parameter is the name of the event to listen to. We will discuss event handling in detail later.

[Related Article: Free Resources For Designers]

Vue Modifiers

Modifier (modifier) is a .special suffix, indicating that the instruction should be binding in some special way. For example, .prevent modifier tells v-on instruction, called after the trigger event event.preventDefault():

<form v-on:submit.prevent="onSubmit"> ... </form>

Later when we explore these features, you’ll see related examples of other modifiers, such as v-on and v-model.

[Related Article: Java Web Services ]

Shorthands in Vue

In the template, the v-prefix acts as a very intuitive hint, which is very effective in identifying Vue-specific attributes. The v-prefix is ​​helpful when you are using Vue.js to add dynamic behavior to an existing tag . However, for some frequently used instructions, you will find it cumbersome to use. At the same time, the prefix becomes less important when building a single-page application (SPA – single page application) that manages all templates by Vue.js. v-Thus, Vue.js of v-bind and v-on the two most frequently used instructions, provides specific abbreviations are used:

v-bind Shorthand

<!-- full syntax -->
< a v-bind:href = "url" > ... </ a >

<!-- Shorthand -->
<a :href="url"> ... </a>
v-on Shorthand

<!-- Full syntax -->
< a v-on:click = "doSomething" > ... </ a >

<!-- Shorthand -->
<a @click="doSomething"> ... </a>

They may look slightly different from the usual we see HTML attributes, but, in fact, : and @ are in line with the attribute name (attribute name) effective character standards, and all browsers support Vue.js able to resolve them correctly.

Also, they don’t appear in the final rendered HTML markup. Shorthand grammar is a completely optional way of writing. However, as you learn more about their usage, you will appreciate this simple and straightforward way of writing, which is a very pleasing usage.

[Related Article: Cloud Computing]

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
JavaScript Hello World.!
External JavaScript Files

Leave a Comment