Vue.js - Get up and Running
Tags: vue, webdev, beginners, javascript
Published: 2022-01-21 18:54:16

Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Mohammad Rahmani</a> on <a href="https://unsplash.com/s/photos/vue.js?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>

###Who is this for?
For developers who are already familiar with frameworks like React, Angular, etc. and want to learn minimum amount of Vue.js features to get their engines running.

I want to give a quick intro of what we need to know if we intend work on a project built with Vue.js. We are gonna start with the important one...**the component structure**.

## Component Structure
The component structure in Vue is pretty straight forward. 
We can divide it into 3 sections.

1. The HTML or (template)
2. The JavaScript or (script)
3. The CSS or (style)

```html
<template>
  <!-- html goes here -->
</template>

<script>
// import other components or libraries using js import
export default {
  data () {
    return {
// define state here
    }
  },
  methods: {
// define functions here
  }
}
</script>

<style>
/* define styles here */
</style>
```

##Component State
In the above code block inside script tags, there is a comment saying _define state here_. It's just that simple.

```html
<script>
export default {
  data () {
    return {
      name: 'Jane',
      age: 32,
      books: ['the dip', 'Norwegian wood'],
      person: {name: 'Jan', gender: 'female'}
    }
  }
}
</script>
```

To **_access the state variables inside the script tags_** you need to use it as **_`this.name`_**. Here the **_this_** keyword refers to the instance which holds the data.

But to **_access it inside template tags_**. You can use the _mustache syntax_. It goes like this.

```html
<template>
  <div>
   <p>{{name}}</p>
   <p>{{age + 10}}</p>
   <p>{{person.gender}} {{books[0]}}</p>
  </div>
</template>
```

We can perform all JS actions inside the braces including function calls. But it isn't preferred unless necessary.

If you want to change value of state variable. You can do this

```javascript
this.name = 'New name'
```
inside any function.

##Template syntax using `v-` directives
Vue uses something called directives which allow us to link JS in script tags with our HTML. So that you can perform JS operations inside the template.
Let's talk about the directives that i found useful and used regularly.

###1. `v-if, v-else-if, v-else` - 
As the name suggests these provide a way to conditionally render required HTML.

```html
<div>
  <p v-if="showIf">Will be rendered if showIf is true</p>
  <p v-else-if="showElsIf">Will be rendered if showElsIf is true</p>
  <p v-else>Will be rendered if above two are false</p>
</div>
```
###2. `v-show` - 
This is similar to the `v-if`. The difference is `v-if` doesn't render to the DOM if the applied condition fails. Whereas `v-show` renders the element to the DOM initially and then hides the element using css display properties if the condition fails.

As we are talking about DOM. I would like to mention that Vue also uses Virtual DOM. You can read more about it in this [blog](https://blog.logrocket.com/how-the-virtual-dom-works-in-vue-js/).

```html
<div>
  <p v-show="age === 20">Show Me</p>
</div>
```
###3. `v-bind` -
I find this to be the most used directive. As the name suggests this is used to bind something, and here that something refers to binding HTML attributes with JS attributes.
Let's see how it works.

```html
<div>
  <button v-bind:disabled="isDisabled">Button</button>
  <div v-bind:class="selected && 'text-blue-500'">
    Blue text
  </div>
</div>
```
This will disable the button if `isDisabled = true`
The Blue text will be blue if `selected = true`. The class name used is a tailwind class. 

Instead of typing the whole `v-bind:disabled` we can write it as `:disabled`. Both are equal. This is called the **_v-bind shorthand_**

v-bind is also used to pass props to a child component.

```html
<div>
  <child :property="newProperty"></child>
</div>
```
`newProperty` is a variable defined in `parent component` that is being passed down to `child component` as `property`.

###4. `v-on` - 
The `v-on` directive is used to add event listeners like onClick, onHover, onFocus, etc. to an element.

```html
<div>
  <button v-on:click="buttonClicked()">Click me!</button>
  <button @click="buttonClicked()">Click me!</button>
</div>
```
Here buttonClicked() is a function that gets called when we click the button.
The first and second lines both work the same way. `v-on:click` is same as `@click`
The second one(`@click`) is called v-on shorthand similar to the v-bind shorthand.

###5. `v-for` - 
Used to loop through an array and render elements dynamically.

```html
<div v-for="item in list">
  <p :key="item">{{item}}</p>
</div>

list = ['item1', 'item2', 'item3']
```
Don't forget to add the `:key` to differentiate the elements.

###6.`v-html` - 
To render real HTML in the template. Say we have a state variable called newHtml.
`newHtml = "<span>Hello Vue!</span>"` 
This can be used in the template as,

```html
<template>
  <div v-html="newHtml"></div>
  <div>{{newHtml}}</div>
</template>

The rendered HTML in browser will be

Hello Vue!
<span>Hello Vue!</span>
```

###7. `v-model` - 
v-model is used to add two way data binding. This is useful to update the value passed to the input or textarea elements as we type. Let's see an example.

```html
<div>
  <input v-model="message">
  <p>{{message}}</p>
<div>
```
The magic of v-model is that it automatically updates the value of message as you enter text in the input box.

This [blog](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwiVv-afvcP1AhW1RWwGHSMzDz4QFnoECCcQAQ&url=https%3A%2F%2Flearnvue.co%2F2021%2F01%2Feverything-you-need-to-know-about-vue-v-model%2F&usg=AOvVaw2ReHth6eRshDj3rzXus7zg) will give you a better understanding of how v-model works.

##Defining functions
We should define functions in the methods function inside script tag. There are also other ways but they don't fall in the current scope of our discussion.

```javascript
export default {
  methods:{
    greet(){
      console.log('Greeting')
    },
    onClick(){
      console.log('Button Clicked')
    }
  }
}
```

##Receive props
We previously saw how to pass props through v-binding. Now let's see how to receive them in the child. 
When props are passed down to the child component we have two ways of receiving them.

```
PARENT: 
<div>
 <child :name="'Jan'" :age="24"></child>
<div>

CHILD:
1st way ->
export default {
  props: ['name', 'age']
  methods:{
  }
}
2nd way ->
export default {
  props: {
    name: String,
    age: Number
  }
  methods:{
  }
}
```

In the second way we define the types of props that we are going to receive. This will help us a lot to identify any errors that might be caused due to unexpected prop value.

This has been a long post I Know!!!. 

Lets end with the final thing "styling".

##Adding Styles
Styles are defined inside the style tags. It works same as normal CSS. 

```html
<template>
  <div class="summary">name</div>
  <p id="id-name">TEXT</p>
</template>
<style scoped>
  .summary {
    font-size: 14px;
  }
  #id-name {
    color: blue
  }
</style>
```
Here we need to add `scoped` so that the styles we added will be applied only to the current component. If we remove it, the styles will be applied globally to all components.

##Conclusion
The things we covered will help you in understanding the flow of a project built with Vue. This is by no means full coverage of all the features.
There are many important topics that we should know to be a better Vue developer.
Topics like - 
####Computed properties
####Getters and Setters
####Watchers
####Mixins
####Vuex
####Life cycle methods
The [official documentation](https://v3.vuejs.org/guide/introduction.html) will help you the most in understanding all the concepts.

Please leave comments to add any suggestion or if you find any mistake. Thanks!!

##Resources to Learn

- https://scrimba.com/learn/learnvue/welcome-to-vuejs-cK8RnSd
- https://vueschool.io/articles/category/vuejs-tutorials/
- https://scrimba.com/learn/learnvue/welcome-to-vuejs-cK8RnSd

Thanks for reading this far. This is my first post on Dev.to.
All the best in your learning journey.

You can reach out to me on [linkedin](https://www.linkedin.com/in/sai-dileep-reddy-aella/).