Vue – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Wed, 10 Mar 2021 16:41:37 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 Vue Computed Deep Structures https://linuxhint.com/vue-computed-deep-structures/ Mon, 08 Mar 2021 18:02:37 +0000 https://linuxhint.com/?p=93479 When it comes to the computation of nested or deep data types like arrays or objects, Vue.js or any other programming language does not automatically detect the hierarchical change in the data. However, we all know that Vue.js provides the watch and computed properties to perform some change variables. But when it comes to nested data changes, Vue.js does not detect that. This post will learn to perform some changes by watching the nested data of arrays or objects.

Before learning about watching nested data in Vue.js, let’s first understand how the watch property works?

Watch Property

The watch property is used to watch a variable and allows the user to perform some desired tasks on the variable’s change.

Example: Watch a Variable

For example, at the change of some variable, we want to console something. The syntax for writing such code in Vue will go like this:

<template>

  <div class="test">

    <h1>This is a testing page</h1>

    <button @click="boolVar=!boolVar">Click</button>

  </div>

</template>

<script>

export default {
  name: "Test",
  data(){
    return{
      boolVar: true
    }
  },
  watch:{
    boolVar(){
      console.log("Button clicked.")
    }
  }
};

</script>

After writing the above code, the web page would be like this.

If we click on the button, the state of the “boolVar” should be altered due to the button’s on-click attribute, and the watch should automatically detect the change in “boolVar” and display the message string on the console.

It worked perfectly fine; the message “Button clicked” is displayed on the console.

But, the watcher fails to detect the change and does not get fired when it comes to watching the arrays or objects. Let’s see a demonstration of that.

Example: Watching an Object

Suppose we have an object in our component, and we want to display the change that happened in the object’s property. In the example given below, I have created an object with the name of “objVar,” which contains two key-value pairs, “item” and “quantity”. I have created a button where I am adding “1” to the template tag’s quantity. Lastly, I am watching the “objVar” object in the watch property and displaying a console message.

<template>

  <div class="test">

    <h1>This is a testing page</h1>

    <button @click="objVar.quantity=objVar.quantity+1">Click</button>

  </div>

</template>

<script>

export default {
  name: "Test",
  data(){
    return{
      objVar: {
        item: "Item1",
        quantity: 1
      }
    }
  },
  watch:{
    objVar(){
      console.log("Button clicked & Quantity = " + this.objVar.quantity)
    }
  }
};


</script>

Now, this code is supposed to display the change in the quantity of the object. But, when we execute the code and click the button on the web page:

You can see in the above gif; nothing is happening in the console.

The reason behind this is that the watcher does not look deep into the values of the objects, and this is the real problem to which we are going to solve now.

Vue.js provides the deep property for watching deep down into the values of objects and arrays. The syntax for using the deep property and watching the nested data is as follows:

<script>

export default {
  name: "Test",
  data(){
    return{
      objVar: {
        item: "Item1",
        quantity: 1
      }
    }
  },
  watch:{
    objVar: {
      deep: true,
      handler(){
        console.log("Button clicked & Quantity = " + this.objVar.quantity)
      }
    }
  }
};

</script>

In this syntax, we have set the deep property to true and rearranged the handler() function.

Now, after changing the code, if we reload the web page and click on the button:

Here you can see that the watcher is working and displaying the message in the console.

Conclusion

After reading this post, watching and computing deep or nested data structures in Vue.js is not difficult anymore. We have learned how to watch the change of a value in an object or array and execute some tasks with the help of the “deep” property of Vue.js.

]]>
Vue Computed Property not updating; Troubleshooting Steps https://linuxhint.com/troubleshoot-vue-computed-property-not-updating/ Mon, 08 Mar 2021 17:47:30 +0000 https://linuxhint.com/?p=93468 Vue.js is a very popular JavaScript library that is known for its reactivity, flexibility, and intuitive API. However, reactivity and flexibility come with some drawbacks, leading to the developer’s performance or a headache. The computed property is a very famous and most known feature of Vue.js, which is used to update some variable or perform some calculation depending upon some other variable’s updation.

This post will try to troubleshoot the problems that occurred when the computed property does not work or update what we want. Let’s have a look at the scenarios, what might go wrong, and Vue Computed Property not updating.

Scenario # 1:

First of all, make sure you did not make any logical error like implementing the wrong logic. To avoid the possible logical errors, check the following things:

  • Verify that variable names are correct.
  • You are taking care of the scopes of the variable using “this”.

Scenario # 2:

The second thing you might have mistaken in the computed property is that you are not caring about the Computed property’s side effects like editing some data inside a computed property or calling other functions. For example, reversing the array within a computed property.

Suppose we have an array in our component.

  data(){
    return{
      arrVar:[1,2,3]
    }
  },

In the computed property, we are reversing the array.

  computed:{
    arrayReverse(){
      return this.arrVar.reverse();
    }
  }

But, when we run the project, it will show an error of ‘Unexpected side effect in “arrayReverse” computed property.’ because it will always do the same task again and again and reverse the original array every time.

So, try to avoid data manipulation in the computed property, and it will work perfectly fine for you.

Scenario # 3:

Another scenario could be that the computed property is stuck in an infinite loop, and it keeps on re-computing something. Since computed property watches every variable included in the computed property and reacts or gets recomputed on the change of any variable involved in this property, if you change the state of any variable inside the computed property, the computed property detects the change. It starts to re-compute itself, and it won’t be able to get out of this infinite loop.

These are some of the possible ways which could lead to the computed property not updating problem.

Conclusion

This post has gone through the most common scenarios the developers faced for Vue Computed property not updating and provided profound and to-the-point troubleshooting steps for each scenario. If you still have not found your solution yet, feel free to ask your questions on the Vue community platforms and get your questions answered within no time.

]]>
Vue Computed with Parameter https://linuxhint.com/vue-computed-with-parameter/ Mon, 08 Mar 2021 10:19:47 +0000 https://linuxhint.com/?p=93463 The Computed property is usually used to compute data from some other data. It is known for its reactivity because whenever a variable involved in some computed property gets changed, the whole property gets recomputed.This post will learn to pass the parameter to computed property and see how to use Vue computed with parameter. Before getting started with passing parameters to the computed property, let’s first understand the computed properties by going through the example.

Examples

Suppose we have two variables named “firstName” and “lastName” in our Vue component:

//..
  data(){
    return{
      firstName: "",
      lastName: ""
    }
  },
//..

Computed Property

We want to compute a “fullName” property that will combine the “firstName” and “lastName” and recompute the fullName whenever any of the two variables “firstName” and “lastName” gets changed. So, the computed property for computing the full name would be like this:

//..
  computed:{
    fullName(){
      return this.firstName + ' ' + this.lastName;
    }
  }
//..

Now let’s create some input fields and bind the “firstName” and “lastName” variables to the input fields and also bind the “fullName” property in the ‘p’ tag to view the instant change on the change of the first anime of the last name. The HTML part of this component will be like this:

Alright! After having all this setup, let’s take a look at our webpage.

If you have successfully written the correct code and run it, you should also have the two input fields on your web page. Let’s try to type the first name and last name and see either the “fulName” property gets computed or not.

Here in the screenshot given above, you can witness the marvelous reactivity of Vue.js using the computed property. You can also witness that it is not like watching a single variable and changing some other variable’s value. Still, it is watching each variable included in the computed property and re-computing the “lastName”. Let’s see how we can pass parameters to the computed property and use it.

Pass parameters to the Computed Property

For passing the parameters to the computed property, we just pass the parameters as we do for the function. For example, in the template, when we have bound the variable “lastName,” we want to pass some string, so the template part of our component would be like this:

Now, in the computed property, the passed parameter can be utilized using the following syntax.

 computed:{
    fullName(){
      return message1 => {
        return `${message} ${this.firstName} ${this.lastName}`
      }
    }
  }

This is how we can pass a parameter to the computed and get it in the property and use it.

If we again look at our web page and type the First name and last name, you can have the same functionality and reactivity, but this time, the parameter passed.

This is how simple and easy it is to pass a computed property parameter and use it.

Conclusion:

The computed property is a very powerful feature of Vue.js, and we have learned that it comes in handy when we have to change them when their dependencies get changed. We have learned to pass the parameter and use it in the computed property.

]]>
Vue.js vs. Django https://linuxhint.com/vue_js_vs_django/ Mon, 14 Dec 2020 06:35:36 +0000 https://linuxhint.com/?p=81446

When you are required to choose a library or framework for building web applications, there is no question that JavaScript libraries are preferred over any other library. But that does not mean that other libraries are not good enough.

Vue.js and Django are both famous JavaScript web frameworks. They are also both open-source tools. Vue.js is famous for building clean, reusable, component-based web applications. Django is a framework that is built on Python and is known for its rapid development and rational code design.

In this article, we will discover some of the basic and more technical differences between Vue.js and Django. This includes the pros and cons of each framework, the companies that currently use these frameworks, integrated tools, and much more.

Difference between Vue.js and Django

Vue.js is a front-end JavaScript framework that generates pages on the client-side. Because it renders pages on the client-side, Vue.js costs more initial load time, but it gives a better experience when it is necessary to navigate between pages.

While Django is a full-stack Python framework and it generates pages on the server-side. Its server-side rendering helps in initially loading the page but while navigating we may have to face performance issues due to the network latency.

Pros of Vue.js

Vue.js is a simple, easy-to-use, and fantastic library for your needs. You can learn it hands-on if you know Html, CSS, and JavaScript. Vue.js is a framework with a fast learning curve signature. The documentation written for Vue.js is also easy to understand and extremely detailed, as well.

The documentation is so well written that you should not feel confused, even when working with it all day. All steps are explained clearly and the Vue.js documentation is one of the best guides available for any web framework. Vue.js is a complete and functional JavaScript ecosystem, and it stands as one of the top front-end frameworks.

Pros of Django

Django is known for its rapid development, and it is an open-source tool. This framework has a great community, as well. Django is an elegant MVC Framework that helps you in writing beautiful code. This framework is free to use, has great documentation, and is very easy to learn, as well. It also provides great packages and libraries to help in development.

Cons of Vue.js

The community of Vue.js is smaller than the other two competitive frameworks, reactJS and Angular. Vue.js does not support fragments, and it only supports multiple root nodes programmatically. Another con of Vue.js is its YXML vs. HTML markup.

Cons of Django

Django is an underpowered templating framework and has an underpowered ORM. Its auto-reload restarts the whole server. Django’s URL dispatcher ignores the HTTP method and has some coupling of internal subcomponents.

Having cons does not necessarily mean that a framework is bad. Actually, every framework comes with the intention of fulfilling some particular need or providing some specific value. It is a well-known fact that every framework has its own features and standards that differentiate it from other frameworks, and it is easy to prioritize one over another according to your needs.

Companies that Use Frameworks

Both of these frameworks are backed by good companies.

Vue.js is backed by a lot of big names, such as:

  • Alibaba
  • Xiaomi
  • Laracast
  • Trivago.com

Django is also backed by some big names, such as:

  • Pinterest
  • Instagram
  • Udemy
  • Robinhood

Conclusion

In this article, we reviewed both the Vue.js and Django frameworks and pointed out their differences. We also discussed the pros and cons of each framework and mentioned the name of the companies backed by these frameworks. Vue.js is becoming quite popular among JavaScript frameworks and front-end web development at an increasing pace, specifically in terms of single-page applications and user interfaces. Meanwhile, Django will have its own recognition of being a full-stack and rapid development framework.

]]>
Vue.js Router https://linuxhint.com/install-vue-router/ Wed, 02 Dec 2020 10:57:27 +0000 https://linuxhint.com/?p=79113

Vue.js is a reactive javascript framework, which is used to build UIs(User Interfaces) and SPAs(Single-page Applications) and developers love to code and feel freedom and comfort while developing applications in Vue.js. For routing purposes, Vue.js does not provide the built-in routing feature. But there is an official third party library with the name of Vue Router for providing this feature. By using this feature we can navigate between the web pages but without reloading. So, in this article, we are going to see how we can install and use Vue Router in Vue.js.

Installation

We can install the Vue router into an existing Vue.js project by running the following command in the terminal

npm install vue-router

After a successful installation, we need to import VueRouter in the main.js file in the src directory as well using the following syntax

import Vue from 'vue'
import router from './router'

Vue.use(router)

After importing the router, you are good to go and use vue-router in your project.

But if you are installing Vue.js using Vue CLI. You won’t need this extra installation step. You can add a vue-router plugin during selecting a preset.

Usage

The usage of the vue-router is very simple and easy to use. First, in the template or HTML

<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</template>

In this pretty simple and clear example of vue-router. We have created simple navigation using router-link components and provide the link using the prop named ‘to’. The router-link works the same as an anchor ‘a’ tag. It is actually rendered as an ‘a’ tag by default. In the router-view, we will have the relative component which matches the route.

In the javascript, we first have to register and import the components to define their routes. We suppose that we have a component named Comp.vue in the views directory to which we will import in the router’s index.js file in the router directory and define it as a route.

To import a component, we use the following statement

import Comp from "../views/Comp.vue";

After importing, we have to define the route now and map it to the component. Like this,

const routes = [

{

path: "/",

name: "Comp",

component: Comp

}

];

We can give multiple routes too, separated by a comma. Like this,

const routes = [

{

path: "/",

name: "Comp",

component: Comp

},

{

path: "/comp2",

name: "Comp2",

component: Comp2

}

];

After defining the routes. Pass routes array to the router instances. So, let’s create the router instance as well

const router = createRouter({

routes // short for `routes: routes`

});

In the end, in the main.js file. We have to create the root instance and mount that as well and inject the routes in it so that the whole app becomes aware of the routes.

createApp(App)

.use(router)

.mount("#app");

By using this injection technique. We can access the router in any component, using this.$router.

We can now programmatically push routes at the click of a button or anything you want, instead of using the router-link component. For example,

methods: {

clickFunc() {

this.$router.push('/about')

}

}

Wrapping up and summary

In this article, we have learned to install Vue Router using different ways and learned to use Vue router programmatically in javascript and in the Vue.js’s template. We have also learned to set up the Vue Router in an existing project in a very easy and step by step detailed guide. If you want to learn more about the Vue Router, kindly visit Vue Router: Official Docs.

]]>
Vue.js Emit Custom Events https://linuxhint.com/vue-js-emit-custom-events/ Wed, 02 Dec 2020 10:23:59 +0000 https://linuxhint.com/?p=79100

Vue.js is a versatile and full-fledged framework for building huge web applications. Any web application is divided into the Components. For example, a simple website that includes a header, sidebar, and some other components. In order to manage and handle this component-based approach, Vue.js offers the parent-child relationship between the components and if we want to send some data across components. Vue.js offers props to send data from the parent to a child component but to send data from the child to the parent; we have to emit custom events. In this article, we learn about firing and listening to custom events.First of all, let’s see how to fire a custom event in Vue.js and then how to listen to that event. The syntax for firing an event in Vue.js is

this.$emit('eventName')

In this syntax, we need to be careful while giving a name to the event because using the same name; we will later listen to this event. In order to listen to this event, we can listen to it as we listen to a click event in Vue.js. For example

<myComponent @eventName="doSomething"></myComponent>

We can write any expression in the inverted commas as well as a function. So let’s try an example to better understand it.

Example

Suppose we have a Component named “parentComponent,” which includes a child component in it with the name of “childComponent” to which we are passing a message using props.

<template>
<h1>Parent Component</h1>
<div>
<h2>Child Component</h2>
<ChildComponent msg="Hello Child" />
</div>
</template>

<script>
import ChildComponent from './components/ChildComponent.vue'

export default {
name: 'ParentComponent',
components: {
ChildComponent
}
}
</script>

In the child Component, we are getting props and showing the message in the ‘p’ tag.

<template>
<p>{{ msg }}</p>
</template>

<script>
export default {
name: "ChildComponent",
props: {
msg: String
}
}
</script>

Now after having these two components set up. Let’s say hello back to our ParentComponent. In order to say hello back, we will first create a button, and at the click of that button, we will call the “helloBack” function. After creating the button, the child component’s HTML would be like this

<template>
<p>{{ message }}</p>
<button @click="helloBack">Send Hello Back</button>
</template>

Let’s create the “helloBackFunc” function in the methods object as well. In which we will emit the “helloBackEvent” along with a “helloBackVar” variable that contains the string “Hello Parent”. After creating a function, the javascript of the child component would be like this

<script>
export default {
name: "ChildComponent",
props: {
msg: String
},
data(){
return{
helloBackVar: 'Hello Parent'
}
},
methods:{
helloBackFunc(){
this.$emit('helloBackEvent', this.helloBackVar)
}
}
}
</script>

We are done with firing the event. Now, let’s move to the parent component for listening to the event.

In the Parent component, we can simply listen to the event, just like we listen to the click event. We will simply listen to the event in the ChildComponent’s tag and calls the “thanks()” function on it.

<ChildComponent @helloBackEvent="thanks($event)" msg="Hello Child" />

In the thanks function, we will assign the passed string to the variable named “thanksMessage”. After creating the function and assigning the passed string to the variable, the javascript of the “parentComponent” would be like this

<script>
import ChildComponent from './components/ChildComponent.vue'

export default {
name: 'App',
components: {
ChildComponent
},
data(){
return{
thanksMessage: ''
}
},
methods: {
thanks(m){
this.thanksMessage = m;
}
}
}
</script>

And bind the “thanksMessage” variable in the template somewhere to see either it works or not.

<template>
<h1>Parent Component</h1>
<p>{{ thanksMessage }}</p>
<div>
<h2>Child Component</h2>
<ChildComponent @helloBackEvent="thanks($event)" msg="Hello Child" />
</div>
</template>

After creating and writing all this code, go to the web page and reload it to get the latest functionalities.

We can see that the props are conveyed successfully to the child component. Now, if we click the button, which is actually in the child component. The thanks message should be displayed right after the parent Component Heading.

As you can see, it is displayed.

So, this is how we can emit or fire the custom events and listen to them in some other component in Vue.js.

Summary

In this article, we have learned to emit custom events in the Vue.js. This article contains a step by step proper example to understand it with a brief explanation along with it. So, we hope this article helps in having better and clear concepts of emitting custom events in Vue.js. For more such useful content, keep on visiting linuxhint.com

]]>
What is Vue.js, and Why is it Cool? https://linuxhint.com/about_vue_js/ Tue, 24 Nov 2020 09:13:57 +0000 https://linuxhint.com/?p=77952

Vue.js is a progressive JavaScript framework, which is used to build UIs (User Interfaces) and SPAs (Single-page Applications). This framework is famous for its fast-paced learning curve. It is such an easy to learn and approachable library that with the knowledge of HTML, CSS, and JavaScript, we can start building web applications in Vue.js. The fast learning curve is kind of a signature of this framework. It is a versatile framework for our need as a library or a full-fledged framework for building huge web apps.

Evan You have created this framework. The idea of Evan You behind this framework is to build the best framework by combining the best features from already existing Angular and react Frameworks. Before building Vue.js, Evan You was working at Google. Inc and worked on Angular based projects. So, he came up with the idea of building his own framework. He picked the best parts of Angular, like template syntax, easy to use, and picked the best parts of React as well, like two-way data binding, the concept of props, component-based approach, and combined them to make a new framework Vue.js better than both of them.

Competition

Every framework has its own features and characteristics, because of which they are known and get priority over any other framework. Vue.js has a record of having the most stars at Github.com for the past 5 years. Although the community of Vue.js is smaller than the react JS, Vue.js stars record is describing and telling about the fans of Vue.js. Whoever uses it once, he/she falls in love with it.

Evolution and Growth

Vue was released way back in 2014. Since then, it is continuously evolving. At the beginning of 2018, Vue.js started beating Angular and becoming more famous in the market. Later, in September 2018, Evan You decided to announce the release of Vue 3.0. Vue.js is continuously evolving with the rapid growth in the usage and community of this framework. The community will keep growing because it was built on the best features combination of Angular and React.

Here are some of the features that we find exciting and the root cause of its rapid growth and make it cool.

Learning Curve & Well written Documentation

Vue.js has one of the best-written Documentation that we have ever seen and suggested. This Documentation takes us through an effortless and step by step guide that one doesn’t feel like hard learning or something different is happening. The learning curve is effortless if we compare it with the react.JS and Angular.

Modular and reusable code

This component-based approach was basically inspired by and picked from the ReactJS. We write code in the form of components to import that component and reuse it wherever we need it. Vue.js offers a single-file component, which makes it a loosely coupled and reusable code.

Mobile Development

There is one underrated feature of Vue.js, which is its cross-platform mobile development. Yes, just like react-native works for react.JS. Vue.js has WEEX developed by Alibaba, Native Script, and Ionic to help in developing mobile UIs. Native Script and WEEX claim that you just have to write the code once and then use/run it wherever you want.

Easy Development

Developers love to code or build applications in Vue.js. They feel freedom and comfort while developing in an unopinionated environment. Vue.js offers the best component-based approach like whatever a developer needs; he can find it in a single .vue file. Developers feel so comfortable and at ease when they don’t have to worry about or take care of the extra structure of a component.

Ecosystem for Development

Vue.js has a very active and vibrant community, which is helping a lot in evolution and growth. Vue.js provides a lot of different tools and libraries to facilitate the development process. The community has some remarkable and note tools and libraries that a coder or developer demands. For example,

  • Vue Router is used for any type of routing.
  • Vuex is used as a centralized store for state management.

Summary

Vue.js is an easy, fast-growing, and adaptable framework to implement in developing applications that anybody with the basic knowledge of web development can get started with because of its invisible learning curve and easy to understand Documentation.

Vue.js provides a full-fledged ecosystem, and it is counted in the top 3 JavaScript front-end frameworks. Honestly, it is the best framework it can be. It is backed by a lot of big names like Alibaba, Xiaomi, and Lara cast. So, it is a must-try framework if you have not tasted it yet.

]]>
Vue.js Conditional Rendering https://linuxhint.com/vue-js-conditional-rendering/ Sun, 22 Nov 2020 11:50:08 +0000 https://linuxhint.com/?p=77791

Vue.js is an easy to learn and approachable library that we can start building web applications in it with the basic knowledge of web development. In Vue.js, developers love to code and feel freedom while developing applications.

In any dynamic web application, conditional rendering is a necessary part. Vue.js provides different ways for conditional rendering, and we can use any of the following ways which suit our purpose:

  • v-show
  • v-if
  • v-else

In this article, we will try these directives provided by Vue.js for conditional rendering and understand them in a better way.

v-show

The v-show only hides the element by disabling its visibility. It hides the element if the value of the passed expression or variable is not truthy.

For example:

<p v-show="isBool">This paragraph is not hidden</p>
<p v-show="!isBool">This paragraph is hidden</p>

v-if

On the other hand, v-if does not hide the element, but it also does not render anything until the value of the passed expression or variable becomes true.

For Example:

<!-- This div is conditionally rendering -->
 <div v-if="isBool">
   <p>This is a paragraph</p>
 </div>

There is an additional feature in the v-if directive as compared to the v-show directive. We can apply it to the template block as well if we do not want to render anything in between that block. Either there is a child component in that or a lot of other elements.

For example:

 <!-- This template is conditionally rendering -->
 <template v-if="isBool">
   <h1>This is a Heading</h1>
   <p>This is a paragraph</p>
 
   <!-- A child component -->
   <Hello msg="Hello Vue" />
 </template>

v-else

We can also use the v-else directive along with the v-if statement in order to conditionally render between any of the two blocks. But, keeping in mind that the v-else block must have to appear right after the v-if block.

For example:

<p v-if="isVar == true">This paragraph will render if 'isVar' becomes true</p>
 <p v-else>Else, this paragraph will get rendered.</p>

We can apply v-else on the template block as well.

 <!-- This div is conditionally rendering -->
 <div v-if="isVar == true">
   <h1>This is a Heading</h1>
 </div>
  <!-- v-else on template block -->
 <template v-else>
   <p>This is a paragraph</p>
 
   <!-- A child component -->
   <Hello msg="Hello Vue" />
 </template>

v-else-if

Just like v-else, we can also use the v-else-if directive along with the v-if directive.

For example:

<div v-if="type == 'car'">
   <p>Car</p>
 </div>
 <div v-else-if="type == 'book'">
   <p>Book</p>
 </div>
 <div v-else-if="type == 'animal'">
   <p>Animal</p>
 </div>
 <div v-else>
   <p>None of the ablove</p>
 </div>

v-if vs. v-show

The v-if and v-show kind of do the same task. They both hide the elements in the DOM based on the truthy or falsy value of the passed expression, but with a subtle difference of hiding and not rendering elements.

If we compare the time and processing cost between these two. The v-if costs more during runtime or toggling, while v-show costs more at the start of rendering. So, it would be wise to use v-show when toggling is purpose. Otherwise, v-if is preferred.

Wrapping up

In this article, we have learned how to conditionally render the DOM in Vue.js using v-if and v-else directives. We have shown some examples and learned about the real difference between v-show and v-if directive. If this article helps you to have a better understanding and concepts, keep on visiting linuxhint.com for such useful content.

]]>
Vue.js Change Style https://linuxhint.com/vue-js-change-style/ Sun, 22 Nov 2020 11:43:47 +0000 https://linuxhint.com/?p=77787

Vue.js is used to build User Interfaces (UIs) and Single-Page Applications (SPAs). It is easy to learn how to use Vue.js and the framework of freedom and comfort that is available while developing applications in this program because it has the best-combined features of Angular and ReactJS. That is why it is known for its easy-to-use and clean coding.

Vue.js provides style binding that you can use to change the style dynamically. You can bind a variable to the style attribute in any HTML tag and change the style when the bound variable is changed. In this article, we will have a look at how to use style binding and change the styling of variables using vue.js.

Inline Style Binding

In vue.js, we can bind variables to style attributes using v-bind directives.

Object Syntax

Just like with inline CSS styling, we can also do inline styling in Vue.js using v-bind directive and curly braces object syntax. You can bind any variable to the style attribute using the following script:

<p :style="{ color: colorVar, fontSize: fontSizeVar + 'px' }"></p>

And, in the script tag and data:

ata() {
  return {
    colorVar: 'red',
    fontSize: 14
  }
}

We can also take the object down to the data and bind that object with the style attribute to make our HTML look cleaner as follows:

data() {
  return {
    styleObject: {
      colorVar: 'red',
      fontSize: 14
    }
  }
}

Now, we will bind the “styleObject” variable to the style attribute as follows:

<p :style="styleObject"></p>

Array Syntax

Vue.js also provides the option to bind multiple variables in array syntax to the single HTML tag, as follows:

<p :style="[basicStyling, extraStyling]"></p>

Multiple Values

Similarly, we can also give multiple values using the array syntax to a CSS property within the inline binding, as follows:

<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>

These are some of the different ways that we can use for binding variables with the style attribute to dynamically change the styling of a webpage.

Summary

This article covered the syntax for binding inline styling. You also learned about the object syntax and array syntax used to bind the values or variables to style attributes in vue.js. If this article proved helpful in giving you a better understanding of vue.js, feel free to continue reading at linuxhint.com for more useful content.

]]>
Vue.js Click Events https://linuxhint.com/vue-js-click-events/ Tue, 17 Nov 2020 11:52:03 +0000 https://linuxhint.com/?p=77108

Vue.js is a very powerful, easy to learn, and approachable library that with the knowledge of HTML, CSS, and Javascript, we can start building web applications in it. Vue.js is built by combining the best features from already existing Angular and react Frameworks. It is a progressive and reactive Javascript framework that is used to build UIs (User Interfaces) and SPAs (Single-page Applications), which is why the developers love to code and feel freedom and comfort while developing applications in Vue.js.If we take a look at the Event Listening and Handling in Vue.js., we will know that it provides a “v-on” directive to listen and handle events. We can use the “v-on” directive to listen to the DOM and perform the required tasks. It also provides many event handlers. However, in this article, we will only learn and keep our focus on the click events. So, let’s get started!

Just like Javascript’s onClick event, Vue.js provides v-on:click for listening events.

The syntax for v-on:click event would be like this:

<button v-on:click="functionName">Click</button>

Vue.js provides a shorthand “@” instead of using “v-on” as well.

<button @click="functionName">Click</button>

Vue.js doesn’t stop in just listening to the click event and calling the function. It will also allow us to directly write any arithmetic operation or anything related to Javascript inside the quotation marks “ ”. Just like this:

<button @click="num += 1">Add</button>

Vue.js provides us to call the method or function in an inline Javascript statement, as shown below:

<button @click="message('Hi')">Show</button>

Using Vue.js’s event handlers, we can access the DOM event as well, using inline statement, by passing the Vue.js’s especially provided “$event” variable into the method’s argument, just like the example below:

<button @click="message('Hi', $event)">Send</button>

Vue.js also provides us to call multiple functions or methods. We can call more than one function and separate them by commas, like this example:

<button @click="first('Hello'), second('Hi', $event) ">Submit</button>

Vue.js provides event modifiers as well.

Event Modifiers

We often need to call modifiers along with the events. So, Vue.js provides some of the following modifiers:

.stop

It will stop the click event’s transmission.

<a @click.stop="doThis"></a>

.prevent

It will prevent the page to reload or redirect.

<form @submit.prevent="onSubmit"></form>

.once

It will trigger the click event only once.

<a @click.once="doThis"></a>

.capture

It is mostly used to add the event listener.

<div @click.capture="doThis">...</div>

We can chain the modifiers as well. However, keep in mind that the order of modifiers does matter, and it will affect the results.

<a @click.stop.prevent="doThat"></a>

Conclusion

In this article, we have covered the whole Click event handling concepts from noob to ninja level. We have learned about the different syntaxes of writing click events and the different ways to use v-on:click directive provided by Vue.js for the ease of developers and different event modifiers. For more useful content like this, related to Vue.js, keep on visiting linuxhint.com.

]]>
Vue.js Components https://linuxhint.com/vue-js-components/ Sun, 15 Nov 2020 10:39:32 +0000 https://linuxhint.com/?p=76830

Vue.js is a progressive javascript framework, which is used to build UIs(User Interfaces) and SPAs(Single-page Applications). We can start building web applications in Vue.js with the basic knowledge of HTML, CSS, and Javascript. Vue.js is built by combining the best features from already existing Angular and react Frameworks. Developers love to code and feel freedom and comfort while building applications in Vue.js.

This component-based approach was basically inspired by and picked from the ReactJS. We write code in the form of components so that we can import that component and reuse it wherever we need it. Vue.js offers a single-file component, which makes it a loosely coupled and reusable code.

Vue.js offers the best component-based approach, like whatever a developer needs; he can find it in a single .vue file. Developers feel so comfortable and at ease when they don’t have to worry about or take care of the extra structure of a component.

In this article, we will have a look at the single-file component, which has a .vue extension. So, let’s have a look at a very simple Vue component example and understand it.

<template>
 <p>{{ message }} World</p>
</template>

<script>
export default {
 name: "hello",
 data(){
   return{
     message: "Hello"
   }
 }
}
</script>

<style>
p {
 font-size: 1em;
 text-align: center;
}
</style>

This a very simple and basic example of a Vue component. In which we can see that the code is divided into three layers. This three-layer syntax is the best part of Vue.js. It satisfies the separation of concern yet being in one single .vue file. We have our template(HTML), logic in Javascript, and styling inside a component.

  • Template
  • Script
  • Style

Template

In this template tag, we write our HTML code. We can bind variables in this as well using the Vue.js data-binding syntax, and we can add some other functionalities in this as well using the Vue.js provided syntax for the respective functionalities.

Script

This is the section where we can write the logic of the component in javascript by following the syntaxes of Vue.js. All the functionalities and logic of a component go here. For example,

  • Importing other components and packages needed.
  • Variable declaration
  • Methods/Functions
  • Life cycle hooks
  • Computed properties and watchers
  • And so on…

Style

This is where we write the styling in CSS of the component, or we can use any preprocessor we want to use.

This is just a glimpse of a component in Vue.js. Let’s take a look at the usage, organization, and data flow between components a little bit.

Import and Use Components

To use the component, we first have to import the component. Otherwise, how can Vue.js know about it? We can simply import a component by adding an “Import” statement at the beginning of the script tag and declaring that component in the “components” object, using the following syntax.

<script>
import Hello from './components/Hello.vue'

export default {
 name: 'App',
 components: {
   Hello
 }
}
</script>

After importing the component successfully, we can use it in the template like this

<Hello msg="Hello Vue" />

This is how simply we can import and use a component in any other component.

Organizing Components

Just like any other application, the Components organization goes like a nested tree. For example, a simple website that includes a header, sidebar, and some other components in a container. The organization of the component would be like this.

Image from Vue.js Official Docs

Data Flow between Components

There can be two types of data flow between components: Parent component to Child Component

We can send data from the parent component to the child component using props: Child Component to Parent Component

We can send data by emitting an event from the Child component and listen to it on the other end (Parent component).

Wrapping Up

In this article, we have gone through a whole journey of understanding a basic component in Vue.js to its usage, its hierarchy, its organization, and implementation of Importing, using, and know-how about communication between components. This article covers a lot of scope of components, yet there is a lot of in-depth knowledge about components out there. So, feel free to visit the Vue.js Official Docs for more information. ]]> Vue.js Data Binding https://linuxhint.com/vue-js-data-binding/ Sun, 15 Nov 2020 10:35:29 +0000 https://linuxhint.com/?p=76838

Vue.js is such an easy to learn and approachable library. So, with the knowledge of HTML, CSS, and Javascript, we can start building web applications in Vue.js. Vue.js is built by combining the best features from an already existing Angular and react Frameworks.

Data binding is one of the most elegant features of Vue.js because it provides reactive/two-way data binding. In Vue.js, we do not have to write a lot of lines to have two-way data binding, unlike other frameworks. One-way data binding means that the variable is just bound to the DOM. On the other hand, two-way means that the variable is also bound from the DOM. When DOM gets changed, the variable also gets changed. So, let’s take a look at both of the data bindings and see the right difference.

One-way Data Binding

If we want to bind any variable, we can simply use Vue.js’s double curly braces syntax or “Mustache” syntax to bind any variable from the relative component instance.

<p> {{ linuxhintText }} </p>

Or, if we want to bind any variable inside an HTML attribute, we can use the v-bind directive.

<div v-bind:class="container"></div>

Vue.js also provides the shorthand for binding variables in an HTML attribute. Instead of writing v-bind:attribute-name, we can only use a colon “:” and attribute name.

<div :class="container"></div>

But these are just data bindings. To demonstrate the two-way data binding, we can use the v-model directive provided by the Vue.js.

Two-Way/Reactive Data Binding

In order to demonstrate reactive data binding, we can use the v-model directive on an input form field. It will internally emit an event and change the variable. To which we can bind somewhere else in the template using Double curly braces or “Mustache” syntax.

<input v-model="linuxhintText" placeholder="Type something" />

<p>You are typing: {{ linuxhintText }}</p></td>

Now, whenever we enter a character in the input form field, we can see that the variable is also updating simultaneously.

Wrapping up

In this article, we have learned how to bind variables in Vue.js using double curly braces or “Mustache” syntax. We have also demonstrated the two way/reactive data binding in Vue.js using the v-model directive. After reading this article, data binding is not a difficult task anymore for a beginner who has just got a start with Vue.js. So, keep on learning the concepts of Vue.js with linuxhint.com. Thank you!

]]>
Vue.js Watch Property https://linuxhint.com/vue-js-watch-property/ Sun, 15 Nov 2020 10:33:22 +0000 https://linuxhint.com/?p=76840

Vue.js is a very powerful and reactive Javascript framework, which is used to build Uis (User Interfaces) and SPAs (Single-page Applications). It is built by combining the best features from already existing Angular and react Frameworks. Developers also love to code or build applications in it.

Vue.js provides the watch property to observe and react to the variables or data change. We can use the watch property to manipulate the DOM when the watched variable gets changed. In this article, we are going to have a look at how we can use watch property, and perform the desired tasks on the change of variable. So, let’s get started.

Watchers

A watcher in Vue.js acts like an event listener to a variable or property. It is used to accomplish several tasks on the change of some specific property. It comes in handy while doing asynchronous tasks.

Let’s demonstrate and understand the concept of the watcher by considering an example.

Example:

Suppose we are building an e-commerce website, in which we have a list of items, and we are building it cart or checkout component. In that component, we need to calculate the amount of a single element concerning the number of items.

First, we are assuming some properties in the data.

data() {
  return {
    itemName: "Item 1",
    itemQuantity: null,
    itemPrice: 200,
    totalPrice: 0
  }
},

In which we will watch the “itemQuantity” property and calculate the total price. We will first do the data bindings in the template,

before writing the code for watching the variable and calculating the total price.

<template>
  <h1>Watcher</h1>
  <p>Item Name: {{ itemName }}</p>
  <p>Item Price: {{ itemPrice }}</p>
  <input type="number" v-model="itemQuantity" placeholder="quantity" />
  <p>Total Price: {{ totalPrice }}</p>
</template>

After writing this code, we will have our web page like this:

Now, we want to change the total price on the change of “itemQuantity” like whenever the user changes the quantity using the input field. The Total Price should get changed. For that purpose, we will have to watch the “itemQuantity” and calculate the total price whenever the “itemQuantity” property gets changed.

So, the watcher for the “itemQuantity” would be like this:

watch:{
  itemQuantity(){
    this.totalPrice = this.itemQuantity * this.itemPrice;
    console.log(this.itemQuantity);
  }
}

Now, whenever the user changes the “itemQuantity”, the total price will be changed in a moment. We don’t have to worry about anything, anymore. The watch property will take care of this calculation now.

Let’s have a look at the web page:

And, let’s try to increase or change the quantity and see some results:

If we change the quantity, let’s say “4”, the total price would be “800”:

Similarly, if we change the quantity to “7”, the total price would be “1400”:

So, this is how the watch property works and helps in reactive development. Reactivity is kind of a signature of Vue.js. Also, the watch property comes in handy while performing asynchronous operations.

Conclusion

In this article, we have learned what is a watch property and how we can use it in Vue.js. We have also tried a real-life example to understand its true implementation. This helps a lot in saving time and speeding up the development process. We hope that you found this article helpful and keep on visiting linuxhint.com for better understanding.

]]>
Vue.js Template Introduction https://linuxhint.com/vue_template_intro/ Fri, 13 Nov 2020 21:23:46 +0000 https://linuxhint.com/?p=76592

Vue.js, which is used to build user interfaces (UIs) and single-page applications (SPAs), combines many of the best features of the JavaScript frameworks Angular and React, and many developers like to use Vue.js because it provides a neutral environment.

Like HTML, Vue.js has a template syntax, and we can use template syntax to bind the DOM with the components data. In this article, we will show you how to insert data into the template syntax and the ways to interpolate different types of data.

Text Interpolation

If we want to bind a variable from the relative component instance, we can use double curly braces, which is also referred to as “mustache” syntax.

<p> {{ linuxhintText }} </p>

Vue.js offers two-way binding, which means that, whenever the value of a variable is changed, the element will be rendered again. However, if we do not want it to be updated, we can use the v-once directive.

<p v-once> {{ linuxhintText }} </p>

Raw HTML Interpolation

Vue.js does not allow for the data binding of plain text, but we can bind raw HTML text using the v-html directive. In the example below, we have a variable in a component called rawHTML that contains some raw HTML text.

data() {

  return {

    msg: "Hello Vue",

    rawHTML: "<p> Linuxhint is <b>Great</b> </p>"

  }

}

We can bind the rawHTML variable using v-html directive as follows.

<template>

  <h1>{{ msg }}</h1>

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

</template>

The div tag will have a p tag inside it.

Attributes Interpolation

In the raw HTML interpolation, we did not use double curly braces to bind the variable. Therefore, if we want to bind a variable inside the HTML attribute, we can use the v-bind directive.

<div v-bind:class="container"></div>

Expressions

Vue.js does not only provide features for binding a variable. Vue.js can be used to write various types of expressions within double curly braces.

{{ count + 1 }}

{{ check ? "true" : "False" }}

{{ arr.sort().reverse() }}

Wrapping Up

In this article, we introduced Vue.js’s simple yet useful template syntax. However, there is a lot more to learn about Vue.js. You can visit the official website of Vue.js here, and you can keep learning about JavaScript with linuxhint.com.

]]>
Install Vue.js in Ubuntu 20.04 https://linuxhint.com/install-vue-ubuntu/ Fri, 13 Nov 2020 05:43:16 +0000 https://linuxhint.com/?p=76535

In this tutorial, we will provide an easy step-by-step process to help you get started with Vue.js. Vue.js is a powerful, progressive, reactive JavaScript framework that is approachable and easy to learn. It provides many different tools and libraries that facilitate the application development process. If you have knowledge of HTML, CSS, and JavaScript, you can start building web applications with Vue.js in no time.

Installation

To integrate Vue.js into a project, you can use the CDN package, NPM, or CLI.

Using the CDN Package

If you want to start learning Vue.js, then it is best to use the CDN package. You can simply add the following script tag in your project to get started.

<script src="https://unpkg.com/vue@next"></script></td>

However, this method is not recommended for production purposes because it can lead to issues with compatibility in the future.

Using NPM

For large-scale production applications, you should install Vue.js using NPM. To use this method, you must have Node.js installed on your machine. If you have not installed Node.js yet, you can find out how by reading our article How to Install Node.js and npm on Ubuntu 20.04 – Linux Hint. If you have already installed Node.js, then you can install Vue.js by running the following NPM command in your terminal

# latest stable
$ npm install vue@next

Using CLI

Vue CLI is a complete package for Vue.js development. CLI is installed globally using the NPM package manager. Before installing Vue.js using the Vue CLI method, you must have some prior knowledge of Node.js and front-end build tools. In addition, we can use either npm or the yarn package manager.

$ sudo yarn global add @vue/cli
# OR
$ sudo npm install -g @vue/cli

After installing the latest version of Vue.js using Vue CLI, you can easily upgrade your projects. To check your version of Vue.js, you can run the following command

vue --version

If you want to upgrade to the latest stable version of Vue.js, you can use the following Vue CLI command.

$ sudo yarn global upgrade --latest @vue/cli
# OR
$ sudo npm update -g @vue/cli

Getting started with Vue.js

To get started with Vue.js, to create a project using Vue CLI using the following command.

vue create demo-app

After running this command, you will be asked to choose a preset.

You can either go with the default or add custom features. You can also use the GUI method to create a Vue project by using the following command.

vue ui

This command will open a window in the browser to help you create a project.

Summary

In this article, we showed you how to install Vue.js using three different methods. After installing Vue.js, you can efficiently manage your web application. If you want to start using Vue.js right away, you can use the CDN package method. However, for production purposes, you should use either the NPM method or the CLI method.

To learn more about Vue.js, you can visit the official website here: Vue.js. ]]>