+ All Categories
Home > Documents > MasteringVue · Contents 2 8 LoopsinVue 31 9 Recipesproject 36 10Vue-cli 56 11UnderstandingVue1les...

MasteringVue · Contents 2 8 LoopsinVue 31 9 Recipesproject 36 10Vue-cli 56 11UnderstandingVue1les...

Date post: 22-May-2020
Category:
Upload: others
View: 4 times
Download: 0 times
Share this document with a friend
37
Transcript

Mastering Vue.js

Oleksandr Kocherhin

January, 2018

1

Contents1 Introduction 61.1 Javascript and Frontend . . . . . . . . . . . . . 71.2 Why Vue? . . . . . . . . . . . . . . . . . . . . . 71.3 Who is this book for? . . . . . . . . . . . . . . 81.4 Technologies . . . . . . . . . . . . . . . . . . . 8

2 Creating first Vue application 93 Methods in Vue 134 Getting event inside method 175 Listening to keyboard events 206 Basic styling in Vue 237 Conditions in Vue 28

Contents 2

8 Loops in Vue 319 Recipes project 3610 Vue-cli 5611 Understanding Vue files 6112 Data inside components 6413 Creating custom component 6714 Styling components 7215 Passing props to components 7516 Validating props 8117 Passing data from child to parent 8618 Communication between child components 9419 Communication between child componentswith-out parent 9920 Refs in Vue 10421 Slots in Vue 107

Contents 3

22 Named slots in Vue 11423 Building tracks admin project part 1 11924 Building tracks admin project part 2 12925 Building tracks admin project part 3 13926 Working with forms 15527 Using radio buttons in Vue 16028 Submitting form 16629 Custom directives 17130 Filters 17931 Computed properties 18332 Mixins 18733 CSS Transitions 19534 CSS animations 20135 Javascript animations 20536 Animations for groups 214

Contents 4

37 Working with servers via HTTP 21838 Global vue-router configuration 22739 Vue resource 23040 Vue router 23841 Deep dive in Vue router 24841.1 Changing route programmatically . . . . . . . 24941.2 Routes with dynamic parameters . . . . . . . 25041.3 Getting parameters from url . . . . . . . . . . 25241.4 Passing an object in a router-link . . . . . . . . 254

42 Router features that every project needs 25742.1 Child routes . . . . . . . . . . . . . . . . . . . . 25842.2 Redirect route . . . . . . . . . . . . . . . . . . 26042.3 Not found route . . . . . . . . . . . . . . . . . 26142.4 Transition on switching page . . . . . . . . . . 26242.5 Securing routes . . . . . . . . . . . . . . . . . . 263

43 Getting started with Vuex 26643.1 Configuring Vuex . . . . . . . . . . . . . . . . . 26743.2 Mutations . . . . . . . . . . . . . . . . . . . . . 27243.3 Getters . . . . . . . . . . . . . . . . . . . . . . 274

Contents 5

43.4 Using helpers for getters . . . . . . . . . . . . 276

44 Actions in vuex 28144.1 Splitting store in several files . . . . . . . . . . 28544.2 Modules in Vuex . . . . . . . . . . . . . . . . . 288

45 Ticket system project. Add ticket page 29745.1 Configuring project . . . . . . . . . . . . . . . 29845.2 Creating add ticket page . . . . . . . . . . . . . 302

46 Ticket system project. Tickets list 31647 Ticket system project. Single ticket page 32848 Ticket system project. Authentication 33949 Deploying a Vue application to amazon 35650 Conclusion 360

6

Chapter 1Introduction

Chapter 1. Introduction 7

1.1 Javascript and FrontendYou chose nice time for learning frontend technologies. Theyare fresh, evolving really fast and are needed in any com-pany with online projects. Improving your skills in frontendcan provide you with a great opportunity to find a good andwell-paid job.

1.2 Why Vue?Building frontend nowadays is as difficult as never before.All business logic was moved from backend side to fron-tend. This makes architecture really difficult. Earlier it wasenough to use jQuery and to do just a bit of javascript onpage, but now it’s really a tough way to build big and scal-able project using something as simple as jQuery. There area lot of frameworks nowadays which are aimed at achiev-ing the best results with creating project of different sizesin easy and pleasant way. I would say that Vue is one ofthe best in this competition. It’s quite new (so you will beon the cutting edge) but there already exist a lot of produc-tion applications. Vue has nice learning curve (but you stillhave a lot to learn) but also takes best from Angular andReact frameworks to create projects with different difficultylevel. It may be as easy as writing your own blog and maybe something really difficult as ecommerce online shop.

Chapter 1. Introduction 8

1.3 Who is this book for?I have about 8 years of frontend experience and want toshare my knowledge with you. I really like Vue frameworkand use it every day to create nice and scalable single pageapplications. In this book we will start from scratch (but youshould still have some knowledge of javascript) and finishwith understanding of all features of Vue. We will go stepby step increasing complexity in each chapter. In this bookyou won’t find only theory. All examples for each chapterare real. We will also build three applications with differ-ent complexity while you will be reading the book. I highlyrecommend you not only to read the book, but also to tryto build all examples and projects step by step with me. Inthis case you’ll receive enough experience to build real ap-plications by yourself later.

1.4 TechnologiesThis book was written with Vue 2.5.9 and willwork with any environment. All projects that wewill implement in the book you can find underhttps://github.com/masteringvuejs/masteringvuejs-projects/tree/master/tracks-admin-page

9

Chapter 2Creating first Vueapplication

Chapter 2. Creating first Vue application 10

In this chapter we will create our first Vue application. Butwe should install Vue first.You can install Vue in different ways. The easiest way is toinclude in your html page Vue script from CDN. You can findCDN link in Vue installation page. package.jsonYou can just put it at the end of the body and you are goodto go.index.html

<html><head></head><body>. . .< s c r i p t src =" https : / / cdn . j s d e l i v r . net /npm/vue

"></ scr ip t ></body>

</html>

There are of course other ways of installation, for examplefrom npm package or by vue-cli but they are more difficultand we will use them later while building more complexapps.For now it’s enough to use just script from CDN.Let’s add also a script where we will write our js to our in-dex.html page.

Chapter 2. Creating first Vue application 11

index.html

<body>. . .< s c r i p t src =" https : / / cdn . j s d e l i v r . net /npm/vue

"></ scr ip t >< sc r i p t src ="code . j s "></ scr ip t >

</body>

Now we should add file code.js in the same folder asindex.html. To start using Vue we always create an in-stance of Vue.code.js

new Vue ( )

Inside our constructor we should pass properties for Vueas an object. And the most important property in objectis el. It indicates which part of our DOM this Vue instanceshould manage.code.js

new Vue ( {e l : ’# root ’

} )

We set el as an element with id root and now we shouldadd such DOM element in our html page.index.html

<body><div id = ’ root ’ > </ div >. . .

</body>

Chapter 2. Creating first Vue application 12

It’s time to render some data on page via Vue. And forthis we should provide data field inside object. Let’s createproperty message inside our data.code.js

new Vue ( {e l : ’# root ’ ,data : {message : ’ Hello Vue ! ’

}} )

Now we want to render this property in our DOM. We canuse special Vue syntax with double curly braces for this.index.html

<div id = ’ root ’ >{ {message } }

</div >

Since Vue controls root element now, it sees the special Vuesyntax, reads our message property from object and ren-ders it instead of double curly braces.We can see now in browser that our message Hello Vue!was successfully rendered. It means that everything worksand we have just built our first Vue app in several minutes.

13

Chapter 3Methods in Vue

Chapter 3. Methods in Vue 14

While creating our first Vue applicationwe used double curlybraces in template. This is the way to say to Vue, what vari-able we want to render.But it’s also possible to use function that will return somevalue, which we can use in our template. And we can createany function that we want inside methods field.code.js

new Vue ( {e l : ’# root ’ ,methods : {getMessage ( ) {return ’ Hello Method ! ’

}}

} )

Now we can call this function inside our template and ourstring is rendered.index.html

<div id = ’ root ’ >{ { getMessage ( ) } }

</div >

And we can even use our variables from data inside any ofour functions. They are all accessible inside this property.

Chapter 3. Methods in Vue 15

code.js

new Vue ( {e l : ’# root ’ ,data : {message : ’ Hello Vue ! ’

} ,methods : {getMessage ( ) {return th i s .message

}}

} )

Here we are using this.message inside our methodgetMessage. And everything is working as before.Very often we need to attach some event to the button andchange some other part of the DOM. In Vue we have a lotof standard directives to use. If you worked with Angular1 before you know what the directives are for sure. In Vuethey are working exactly in the same way.Basically, directives are just pieces of javascript code, some-times with template which is tied to element on which weare using our directive.And there is a directive v-on which helps us to bind eventsto elements. The most popular event is of course click.Let’s add button and change our variable inside Vue.index.html

<button v−on : c l i c k = ’onSubmit ’ >Submit </button>

And we should add onSubmitmethod now.

Chapter 3. Methods in Vue 16

code.js

methods : {getMessage ( ) {return th i s .message

} ,onSubmit ( ) {th i s .message = ’ Submitted ’

}}

Now when we click on our submit button the message onthe screen is changed automatically to Submitted.There is a small trick here. As writing v-on:click takesquite long and we are using it a lot there is an alias for this.We can use @ instead of v-on:index.html

<button @cl ick = ’onSubmit ’ >Submit </button>

As you can see, everything works as before.

17

Chapter 4Getting event insidemethod

Chapter 4. Getting event inside method 18

Quite often we need to get access to event when it hap-pens. And in Vue it’s quite easy to do it. Let’s add mousemoveevent on our block with message.index.html

<div @mousemove= ’hoverMessage ’ >{ { getMessage ( ) } }

</div >

Now we can add this method. As a first parameter we willget event that happens. Let’s check it in console.code.js

methods : {. . .hoverMessage ( event ) {console . log ( ’ hoverMessage ’ , event )

}}

Now onmousemove we are getting ourmouseevent in con-sole. Let’s render X and Y from our event on the screen tosee the position of cursor.First we should create x and y with default values.code.js

data : {. . .x : 0 ,y : 0

}

Now let’s assign them when our mousemove happens.

Chapter 4. Getting event inside method 19

code.js

hoverMessage ( event ) {th i s . x = event . c l i en tXth i s . y = event . c l i en tY

}

Now let’s render them on the screen.index.html

<div >Posi t ion : { { x } } | { { y } }

</div >

As you can see in browser, when we hover on our HelloVue the message position of our cursor changes and werender new positions on the screen.

20

Chapter 5Listening to keyboardevents

Chapter 5. Listening to keyboard events 21

Quite oftenwe need to control keyboard events in javascript.For example we can use space for play/pause of video orescape for going out of edit mode.And the is a nice directive v-on:keyup to listen to the eventsfrom keyboard. Let’s try it through a real example. We cancreate input and handle keyboard events of what the useris typing.First we should add input in our html page.index.html

<input type = ’ text ’ />

Now let’s add a keyup event for it.index.html

<input type = ’ text ’ v−on : keyup= ’onKeyUp ’ />

v-on:keyup here is a method from Vue. We can also useshorthand for v-on.index.html

<input type = ’ text ’ @keyup= ’onKeyUp ’ />

We should add onKeyUpmethod in Vue instance now.code.js

onKeyUp ( event ) {console . log ( ’onKeyUp ’ , event )

}

While typing in browser we see our event in console. Wecan read a key from it and do whatever we want with it.

Chapter 5. Listening to keyboard events 22

But let’s say that we want to listen only to a single key, forexample, to escape key. In Vue there is an easy way to doit. We can just set in keyup what key we want to listen to.This is called a modifier.index.html

<input type = ’ text ’ @keyup . space = ’onKeyUp ’ />

As we can see now, our onKeyUpmethod is being fired onlywhen we are hitting space. We can add any amount of keyswith modifiers.index.html

<input type = ’ text ’ @keyup . space . esc = ’onKeyUp ’ />

In browser now we will see console.log only by hitting es-cape or space.

23

Chapter 6Basic styling in Vue

Chapter 6. Basic styling in Vue 24

When we want to style elements in Vue, we are doing it inthe same way as for normal html and css.Let’s add a div with class test and apply some styles for thiselement in head section.index.html

<head><sty le >. tes t {background : green ;

}</ s ty le >

</head><body><div c lass = ’ test ’ > Test </ div >. . .

</body>

As we can see styles are applied. But what if we want toapply styles based on some condition in Vue? We can usev-bind syntax for this.index.html

<div v−bind : c lass ="{ tes t : i sAc t i ve }" > Test </ div >

So here we used v-bind directive with class and passed astring with object inside. A key of the object is the class thatwe want to apply and value is a boolean from Vue instance.To make this working we should add isActive variable inVue.

Chapter 6. Basic styling in Vue 25

code.js

data : {i sAc t i ve : true

}

In browser our Test container is rendered with green back-ground now. If we change isActive to false, our class won’tbe applied.It’s also possible to store classes as string in Vue and thenrender inside v-bind.Let’s add myTestClass variable inside data.code.js

data : {myTestClass : ’ test ’

}

And to pass this class inside our div we need to bind it tothis variable.index.html

<div v−bind : c lass = ’myTestClass ’ > Test </ div >

As writing v-bind each time is not that efficient, there isalso an alias for this. We can simply use colon.index.html

<div : c lass = ’myTestClass ’ > Test </ div >

Sometimes we want to apply several classes together. InVue we can use array notation for this.

Chapter 6. Basic styling in Vue 26

Let’s add a new variable with class name inside data object.code.js

data : {myTestClass : ’ test ’ ,errorClass : ’ error ’

}

Then let’s apply both classes in our template.index.html

<div : c lass = ’ [ myTestClass , errorClass ] ’ > Test </ div>

In browser we see, that our container has not only greenbackground but also red color.It’s also possible to apply styles inline, without classes. Wecan write a bunch of styles as an object and apply themwith style directive to our element.First let’s create an object with styles.code.js

data : {myTestStyles : {background : ’ green ’

}}

Don’t forget that you need to write all styles as strings. Sowrap them in single quotes.We can apply it to our container now.

Chapter 6. Basic styling in Vue 27

index.html

<div : s t y l e = ’myTestStyles ’ > Test </ div >

We can also apply several blocks together with array nota-tion.Let’s add one more block with styles.code.js

data : {myTestStyles : {background : ’ green ’

} ,er rorSty les : {color : ’ red ’

}}

Then apply it, tooindex.html

<div : s t y l e = ’ [ myTestStyles , er rorSty les ] ’ >Test

</div >

As you can see, we got the same result as before. But themain difference is that with style all styles are applied inlineand with class as normal classes.And there is one more hidden benefit of Vue. When youapply some styles that require vendor prefixes (for exampletransform) Vue will automatically apply all prefixes.

28

Chapter 7Conditions in Vue

Chapter 7. Conditions in Vue 29

Very often we need to manipulate our DOM to hide andshow some elements on the screen. We can do it in severalways with Vue.Let’s first add Submit button, isVisible variable and onSubmitmethod.index.html

<button @cl ick = ’onSubmit ’ >Submit </button>

code.js

data : {i s V i s i b l e : fa l se

} ,methods : {onSubmit ( ) {th i s . i s V i s i b l e = true

}}

Now when we click on button, isVisible variable will beset to true.Now let’s add block with text, that we want to show only incase isVisible variable equals true.index.html

<div v−show= ’ i s V i s i b l e ’ > Text </ div >

Here we used special v-show directive which appliesdisplay:none on element, based on isVisible value.When we inspect our element we see that it is always ren-dered, but has display:none styles by default. When we

Chapter 7. Conditions in Vue 30

click on button, display:none is being removed.Sometimes we want to remove element from page com-pletely, not just hide it. We can use v-if directive for this.index.html

<div v− i f = ’ i s V i s i b l e ’ > Text </ div >

It works in the same ways as v-show, but removes DOMelement from page completely.There is also v-else directive that you can use togetherwith v-if.Let’s create new div after first div.index.html

<div v−else >Else </ div >

As you can see, else block is rendered by default now. Itlooks quite useful, but you should be careful with it. Ifyou move this element, or put one more element betweenthem, it won’t work. Thats why I always use v-if block withnegation but not v-else.index.html

<div v− i f = ’ ! i s V i s i b l e ’ > Else </ div >

In this chapter we tried the most popular ways of workingwith conditions in Vue.

31

Chapter 8Loops in Vue

Chapter 8. Loops in Vue 32

Basically all frontend is about rendering lists. And we cando it easily in Vue using v-for directive.But we need to create our data inside Vue first. Let’s as-sume that we have a list of users and want to render themon the screen.code.js

data : {users : [{ id : 1 , name: ’ Alex ’ , i sAc t i ve : true } ,{ id : 2 , name: ’ John ’ , i sAc t i ve : true } ,{ id : 3 , name: ’ Jack ’ , i sAc t i ve : fa l se }

]}

Now let’s render them in template using v-for directive.index.html

<ul >< l i v−for = ’user in users ’ >{ { user .name} }

</ l i ></ul >

As you can see, we are passing construction user in users.Users here is our variable from data. User is just a refer-ence to each record inside our array. We can name it as wewant. It just helps us to get access to each element of thearray. We can use it inside v-for to render information ofeach element.As you can see it’s really easy to render lists with Vue insidea template.

Chapter 8. Loops in Vue 33

We can also render more markup inside each element if wewant.index.html

<div v−for = ’user in users ’ ><h1>{{ user .name}} </h1><div >i sAc t i ve : { { user . i sAc t i ve } }

</div ></div >

Sometimes we need to get index of each element in thearray. To do this we can change a bit our v-for directive.index.html

<div v−for = ’ ( user , index ) in users ’ ><div >

Index : { { index } }</div >

</div >

As you can see, we wrote user, index like they are param-eters in a function. In such way we have access to index ofeach element inside v-for.Sometimes our data can be more difficult. Let’s say each ofour users has todos property, that we want to render. Wecan just add them to a first user to test.

Chapter 8. Loops in Vue 34

code.js

{id : 1 ,name: ’ Alex ’ ,i sAc t i ve : true ,todos : [’ Learn Vue ’ ,’ Create f i r s t Vue app ’

]}

Now we can put v-for inside v-for to render todos foreach user.index.html

<div v−for = ’user in users ’ ><h1>{{ user .name}} </h1><div v−for = ’ todo in user . todos ’ >{ { todo } }

</div ></div >

In browser we can see the list of users with their todos un-der each name.There is also a possibility in v-for to be applied not on anarray but on a number. Than v-forwill render all elementsfrom 1 to this number.index.html

<div v−for = ’number in 10 ’>{ {number} }

</div >

Chapter 8. Loops in Vue 35

Now on the screen we can see the list of numbers from 1to 10.In this section we checked the most popular ways of usingv-for to render lists.

This is the end of the preview sample

Enjoyed the preview?

Head over to https://masteringvuejs.comto download the full package!


Recommended