DEV Community

Cover image for Vue Directives and many more
Githu Kelvin
Githu Kelvin

Posted on

Vue Directives and many more

Hello developers here is my second journey into this wonderland of vue.js .It is an awesome journey first let me point out why i like vue even if am just a beginner .

NOTE Below is image with backtick between mustache note that i added those backtick when publish to avoid this error whoops, something went wrong: liquid error: liquid variables are disabled So it is not a vue.js syntax remember so .happy reading

backtick

Here are some of my points:-

  • Vue keeps the html same no knew syntax or concept introduced
  • Vue is declarative in terms of you just describe your output and Vue just does the other work
  • Lastly it is easy to maintain.Or let me say at this level this why i love it .

So on this Second tour on the wonderland (vue) i got to explore not much but the core basics so here it is:-
  1. Instantiating a Vue app using CDNs
  2. data function
  3. Interpolation
  4. Vue Directives
  5. Conditional rendering
  6. ref and $ref

Creating a vue app using CDN

There is 3 type of CDNs to use vue with:-

1.unpkg which i will use over here below it is the script:-



    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>


Enter fullscreen mode Exit fullscreen mode

2.jsdelivr



    <script src="https://cdn.jsdelivr.net/npm/vue@3.3.4/dist/vue.global.min.js"><script>


Enter fullscreen mode Exit fullscreen mode

3.cdnjs -> It has many files thhe link to it is here cdnjs

After you have placed any of link in the html either you can create a new js file to write your code or just use it in the html file under the script tag i will use script tag here i what it looks



         <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>v-on  directive</title>
        </head>
        <body>
        <div id="app"></div>
        <script src="https://unpkg.com/vue@next"></script> //link to the cdn
                <script>
                    //My code here
                </script>
        </body>
        </html>


Enter fullscreen mode Exit fullscreen mode

This
div it is used by vue to control our app by vue it doesn't need to be a div it can be any html tag .This is also the the same for the id it can be a class but recomended to use id because it is unique

<div id="app"></div>  
Enter fullscreen mode Exit fullscreen mode

After this under the script tag we can start creating our app like before



    <script>
       let app =  Vue.createApp({});
         let vm = app.mount("#app")
    </script>


Enter fullscreen mode Exit fullscreen mode

The code above by doing so you will have started an vue app and we can start manupilating our website.

The Vue in the code is an object that has function createApp that it argument it is an object and in that object it is where we will control our vue website.let start.

The data function

The data function is one of the values of our object of createApp function
The data function it is a function that just returns an object and it must be an object and in it what we return can be used as output in our website let the fun begin:
In this funtion we wan return anything but keynote is that The name of the function must be data which it is a reserved word in vue

So in our script let start out putting:-
As i said before we can return anything json,object,array,numbers,strings anything but not functions.



    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
       let app =  Vue.createApp({
           data(){
                return{
                    title:'v-for:iterate over[]  or {}',
                    cities:['Dhaka','Chittagong','Rajshahi','Khulna','Barishal','Sylhet','Rangpur','Mymensingh'],
                    json:[
                        {Brand:'Toyota',model:'Supra',year:2002},
                        {Brand:'Mercedes',model:'Amg',year:2011},
                        {Brand:'Honda',model:'NSX',year:2014},
                        {Brand:'Nissan',model:'GT-R',year:2017},
                        {Brand:'Toyota',model:'Camry',year:2014},
                        {Brand:'Mercedes',model:'G-wagon',year:205},
                        {Brand:'Honda',model:'Civic',year:2010},
                        {Brand:'Nissan',model:'Nism0',year:2019},
                    ],
                    car:{Brand:'Nissan',model:'GT-R32',year:2013}, 
                    cars:[
                    {Brand:'Nissan',model:'GT-R32',year:2013},
                    {Brand:'Nissan',model:'GT-R35',owner:"kelvin"},
                    {Brand:'Toyota ',owner:'Nash',price:"30m"}
                    ]


                }
            }

         });
         let vm = app.mount("#app")
    </script>


Enter fullscreen mode Exit fullscreen mode

As illustrated above you can see multiple data types. The above code i will use it to illustrate the other parts.

Interpolation

This is the folowing this is outputing data on the website using Mustachetag or this {{}}
example took the part of it .



    <div id="app" >
        <h2>`{{ title }}`</h2>

    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
        <script>
           let app = Vue.createApp({
            data(){
                    return{
                        title:'v-for:iterate over[]  or {}',
                    }
                }

            });
            let vm = app.mount("#app")
        </script>


Enter fullscreen mode Exit fullscreen mode

Here it is the output.

image for interpolation"

Fig.1.Image for interpolation

Above it is interpolation or using Mustachetag to display

Vue directives

Below it is a list of vue directive

  1. v-html
  2. v-for
  3. v-model
  4. v-text
  5. v-if,v-else-if,v-else
  6. v-on
  7. v-cloak
  8. v-bind
  9. v-once
  10. v-is
  11. v-show

The list is some of v-directive there is also custom v-directives
What is a v-directive composed of



        v-dir_name:v-attr="v-argument"


Enter fullscreen mode Exit fullscreen mode

1.v-html

This directive gives you ability to output html code in vue but not recomended since it introduces xss vulnerability



      <div id="app">
        <h2>`{{ title }}`</h2>
        <h1>`{{ html }}`</h1>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
       let app= Vue.createApp({
            data() {
                return {
                    title:"Illustrating v-html",
                    html: "<h1>This is heading</h1>"
                }
            }
        });

        let vm = app.mount("#app");
    </script>



Enter fullscreen mode Exit fullscreen mode

Here it is output of the above code

image of Mustachehtml

As output showing it can't compile the html.below is how //v-html is used



     <div id="app">
        <h2>`{{ title }}`</h2>
        <h1 v-html="html"></h1>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
       let app= Vue.createApp({
            data() {
                return {
                    title:"Illustrating v-html",
                    html: "<h1>This is heading</h1>"
                }
            }
        });

        let vm = app.mount("#app");
    </script>

Enter fullscreen mode Exit fullscreen mode

Output below as it shows now the code was compile as a html code remember don't use it occasionally.

vhmtl image

2.v-text

This v-directive is the same as interpolation or the Mustachetag




    <div id="app">
        <h2>`{{ title }}`</h2>
        <h2  v-text="text"></h2>
        <h1 v-html="html"></h1>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
       let app= Vue.createApp({
            data() {
                return {
                    title:"Illustrating v-html",
                    text: "Illustrating v-text",
                    html: "<h1>This is heading</h1>"
                }
            }
        });

        let vm = app.mount("#app");
    </script>


Enter fullscreen mode Exit fullscreen mode

The result for this snippet is as below

image for v-text
The selected is the output for the v-text

3.v-once

This directive will just render an element just once.And note to take is that the v-once doesn't require a v-attribute and v-argument as shown below



          <h2>`{{ title }}`</h2>
        <h2  v-text="text"></h2>
        <h1 v-html="html"></h1>
        <h2 v-once  v-text="vonce"></h2>
        <h2>`{{ vonce}}` don't have v-once</h2>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
       let app= Vue.createApp({
            data() {
                return {
                    title:"Illustrating v-html",
                    text: "Illustrating v-text",
                    html: "<h1>This is heading</h1>",
                    vonce: "This is v-once that renders once  only"
                }
            }
        });

        let vm = app.mount("#app");

Enter fullscreen mode Exit fullscreen mode

The output is as below :-

output

Image above shows two output one has v-once the other one doesn't have.
So we will change the value of vonce in our console to see how v-once works the image below illustrates so:-

without v-once

Above is how v-once is used as shown in the image even after the value was changed the tag that has v-once it is not rerendered again.

3.v-cloak

To illustrate v-cloak maybe a little hard.but as you are developing your app and refreshing the browser to see the output in a short moment you can see the Mustachetag or any other vue component .So to handle this we use v-cloak on our parent div also the directive doesn't have v-attribute and v-argument . After this in your css workspace do the following



    //vue workspace

    <div class="container" v-cloak>
        //Here other property
    </div>

    //Css workspace
    [v-cloak]{
        display:none;
    }

Enter fullscreen mode Exit fullscreen mode

Doing in so the output will be displayed once processing or compilinga is done.

4.v-pre

Due to the fast compilation of vue maybe unable to illustrate but this directive purpose is if there are elements that are static instead for compiling them over and over again and there are not part or used by vue to skip them . Also it is the same for (v-once,v-cloak) no attribute name or argument



    <h2 v-pre>This is a static paragraph</h2>

Enter fullscreen mode Exit fullscreen mode

This snippet will not be compiled.

5.v-bind or : for shorthand

This is one of important directive in vue as name says binds vue data to html elements attribute
example:-



     <div id="app">
        <h2>`{{ title }}`</h2>
        <h2  v-text="text"></h2>
        <h1 v-html="html"></h1>
        <h2 v-once  v-text="vonce"></h2>
        <h2>`{{ vonce}}` don't have v-once</h2>
        <a v-bind:href="link" target="_blank">My linked in profile</a>
        <br>
        <a :href="link" target="_blank">My linked in profile</a>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
       let app= Vue.createApp({
            data() {
                return {
                    title:"Illustrating v-html",
                    text: "Illustrating v-text",
                    html: "<h1>This is heading</h1>",
                     link: "https://www.linkedin.com/in/kelvingithu/",
                    vonce: "This is v-once that renders once  only"
                }
            }
        });

        let vm = app.mount("#app");
    </script>

Enter fullscreen mode Exit fullscreen mode

Lets focus on this snippet of part of above snippet



     <a v-bind:href="link" target="_blank">My linked in profile</a>
        <br>
        <a :href="link" target="_blank">My linked in profile</a>

Enter fullscreen mode Exit fullscreen mode

Using v-bind or : for shorthand we can pass link value that is data value of vue to our anchor tag as shown below

elements

As the image above illustrate we can have passed this https://www.linkedin.com/in/kelvingithu/ to the href attribute .
The v-bind or : can be used to pass or bind vue data to any html attribute that needs an argument eg src,href,classes,ids and many more.

6.v-on

To illustrate this well will be on the methods since v-on is an event listener like click,mouseover,input and many more it has a shorthand for @ .@ is it's shorthand

7.v-is

This changes a HTML tag from one to another it is working but it is deprecated as of vue 3.1
example:-



    <div id="app">
        <h2 v-is="`p`">`{{ title }}`</h2>
    </div>

Enter fullscreen mode Exit fullscreen mode

v-is

As image above shows the h2 was changed to p tag.

8.v-model

Another important directive must know.
It creates two way data binding to collect and display the output to the user through the input tag. More understanding is when taking user inputs



    <div id="app">
    <input type="text" v-model="username">

    </div>
    <script src="https://unpkg.com/vue@next"></script>
    <script>
    let app = Vue.createApp({
        data(return{
            username:''
        })
    })
    </script>

Enter fullscreen mode Exit fullscreen mode

The above code if user enters any value that value can be accessible in dat in vue in username also it is the same if there is value in username it will be accesible to the user that is two way data binding.

9.v-for

This for printing arrays and object to our DOM.



       <div id="app">
        <!-- v-for  in array -->
        <h2 style="color:#ad0889e3">`{{title}}`</h2>
        <p style="color:rgba(189, 16, 16, 0.932)">v-for in array</p>
       <ul >
        <li v-for="(elem,index) in cities" :key="index" :ref="`li`+index">
            `{{elem}}`
        </li>
       </ul>
       <!-- v-for in objects -->
       <p style="color:rgba(0, 0, 0, 0.932)">v-for in object</p>
       <ul>
        <li v-for="(val,prop,index) in car" :key="index" >
            `{{index}}` `{{prop}}` `{{val}}`

        </li>
       </ul>
         <!-- v-for in json -->
            <p style="color:rgba(162, 165, 9, 0.932)">v-for in json</p>
            <ul>
                <li v-for="(elem,index) in json" :key="index">
                    `{{index}}` `{{elem.Brand}}` `{{elem.model}}` `{{elem.year}}`
                </li>
            </ul>

            <!-- v-for if the json has diferrrent values -->
            <ul v-for="(elem,index) in cars" :key="index">
                <li v-for="(val,prop,index) in elem" :key="idex">
                    `{{prop}}`:`{{val}}`
                </li>
            </ul>

    </div>
    <script src="./index.js"></script>
    <script>
        const app = Vue.createApp({
            data(){
                return{
                    title:'v-for:iterate over[]  or {}',
                    cities:['Dhaka','Chittagong','Rajshahi','Khulna','Barishal','Sylhet','Rangpur','Mymensingh'],
                    json:[
                        {Brand:'Toyota',model:'Supra',year:2002},
                        {Brand:'Mercedes',model:'Amg',year:2011},
                        {Brand:'Honda',model:'NSX',year:2014},
                        {Brand:'Nissan',model:'GT-R',year:2017},
                        {Brand:'Toyota',model:'Camry',year:2014},
                        {Brand:'Mercedes',model:'G-wagon',year:205},
                        {Brand:'Honda',model:'Civic',year:2010},
                        {Brand:'Nissan',model:'Nism0',year:2019},
                    ],
                    car:{Brand:'Nissan',model:'GT-R32',year:2013}, 
                    cars:[
                    {Brand:'Nissan',model:'GT-R32',year:2013},
                    {Brand:'Nissan',model:'GT-R35',owner:"kelvin"},
                    {Brand:'Toyota ',owner:'Nash',price:"30m"}
                    ],
                     link: "https://www.linkedin.com/in/kelvingithu/"



                }
            }
        })
            let vm = app.mount("#app")

    </script>


Enter fullscreen mode Exit fullscreen mode

The output for the code

v-for

10.Conditional Rendering

conditional rendering use v-directive of v-if ,v-else-if and v-else.
Note to take home is that when using this directive they should be adjancent to each other and no other elements should appear between them or else it will not work.
Example:-



      <div id="app">
        <p v-if="val">This an Even number</p>
        <p v-else>This is an odd number</p>

        <p v-if="fruit==='banana'">This a banana</p>
        <p v-else-if="fruit==='apple'">This an apple</p>
        <p v-else>This is another fruit</p>
    </div>
    <script src="./index.js"></script>
    <script>
       let app= Vue.createApp({
            data() {
                return {

                    val:true,
                    fruit:'banana'
                }
            }
        });

        let vm = app.mount("#app");
    </script>


Enter fullscreen mode Exit fullscreen mode

Lets start with this code block



    <p v-if="val">This an Even number</p>
    <p v-else>This is an odd number</p>    

Enter fullscreen mode Exit fullscreen mode

The code block above we pass val data from vue that is true.we could have passed it directly but the reason behind this is :-
1.To show we can pass vue data
2.To change the value to see the conditional rendering
Lets see the output :-
image below is when we compile our code since val is true will print first p tag with This is an even number

even

Now lets change the value of val to false in the console here it is the output:-it will print second tag with This an odd number
odd
lets inspect the second block which have v-if,v-else-if,v-else:-
The purpose of this is to show we can do simple js code in these v-directives to compare



      <p v-if="fruit==='banana'">This a banana</p>
        <p v-else-if="fruit==='apple'">This an apple</p>
        <p v-else>This is another fruit</p>

Enter fullscreen mode Exit fullscreen mode

Here it is the output:-

As fruit is set to banana it will output This is a banana.

default

When we change the value of the fruit to apple in the console the output will be This is an apple

apple

When we change the value of the fruit to another fruit lets say kiwi in the console the output will be This is an another fruit

kiwi

Another keynote to add is that in v-if,v-else-if,v-else it completely removes the element from DOM .

11.v-show

This v-directive adds a styling of display:none to the element it doesn't remove the element form the DOM. If false else if the argument returns true it removes the styling



       <p v-show="false">This will not show</p>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
       let app= Vue.createApp({
            data() {
                return {

                }
            }
        });

        let vm = app.mount("#app");
    </script>


Enter fullscreen mode Exit fullscreen mode

As the image below shows

v-show

it adds the styling of display none to our paragraph.That is how v-show works.

ref and $refs

ref and $ref works like ids but in more use case it can be illustrated by using child component passing them to parent component and retrieving them.



     <div id="app">
        <h2 ref="title"  v-if="control" id='title'>`{{title}}`</h2>
        <p ref="msg" id="msg">`{{msg}}`</p>
    </div>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
        const app = Vue.createApp({
            data(){
                return{
                    title:"Ref Attribute & vm.$refs",
                    msg:"access page elem. $ child comp",
                    control:true
                }
            }

        })
            let vm = app.mount("#app")
            let  h2 = vm.$refs.title

Enter fullscreen mode Exit fullscreen mode

$refs-> This is vue keyword that has all ref
ref-> we create ref as shown in the code below we use ref="any value"



    <h2 ref="title"  v-if="control" id='title'>`{{title}}`</h2>
        <p ref="msg" id="msg">`{{msg}}`</p>


Enter fullscreen mode Exit fullscreen mode

Images below we can see that we have access or we have or p and h2

ref attribute
This image below we can even console the whole tag with it value

h2ref

Happy Developing .Bug free CodesπŸ˜ŽπŸ˜‹

Next stage is Computed, Methods, and Handling Forms

Top comments (0)