Vue Js Crash Course Part-1
Story: In this article series. we will build a sample product detail page from scratch using vue.js and walkthrough its features. It's recommended to have intermediate knowledge of HTML, CSS, and JS. We will start with a barebone HTML, CSS skeleton, and a plain js file.
Note: Include vue.js CDN link in the project as shown below
index.html
app.js
Now we have our index.html and app.js with Vue instance initialized. Vue instance is the root of the project. it receives options as an object. Options object has a variety of properties to make actions and drive the desired application behavior.
With this, the Vue instance is connected to the HTML element and establish a relationship between Vue instance and HTML Dom.
Data:
when a Vue instance is created it has a data object to store the information.
To display product title and product price on the webpage. we need to embed the product title and product price inside the h1 tag using javascript expression(double curly braces) as shown in the image below.
Output:
Oops!. Our Vue first app is created and it's working. When you change product title or price in the app.js. it will be automatically updated in the browser because the data object is linked to the Dom.
Vue handles these changes using a concept called reactivity. reactivity will establish a relationship between the data object and HTML elements we referenced in the index.html. In this scenario, the h1 tag is the element we referenced. You can play around adding more properties to the data object and referencing the HTML elements with expressions.
Attribute binding:
The word itself will indicate the binding of the attributes. We are going to bind the data object properties to the HTML element attributes.
Vue offers several directives to bind javascript expressions:
v-html
v-bind
v-on
v-model
v-if
v-for
v-bind:
we will use v-bind directive to display the image from application Vue instance data object
Now we will display the banner image property to image src attribute using v-bind directive. v-bind fetches the image path from the Vue instance dynamically binds to the src attribute. if we change the bannerImage . It will rerender the dynamic image path and display the updated image.
output:
Hooray!. Image appears. The image displayed successfully.
v-for: directive is used to loop array of elements
output:
Conditional Rendering
by using v-if directive we can display elements conditionally
Final Product Page Preview:
Conclusion:
The completed code can be found on codepen & Github: