Vue Directives.pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
Vue Directives Vue Directives Vue directives are special HTML attributes with the prefix v- that give the HTML tag extra functionality. Vue directives connect to the Vue instance to create dynamic and reactive user interfaces. With Vue, creating responsive pages is much easier and requires less...
Vue Directives Vue Directives Vue directives are special HTML attributes with the prefix v- that give the HTML tag extra functionality. Vue directives connect to the Vue instance to create dynamic and reactive user interfaces. With Vue, creating responsive pages is much easier and requires less code compared to traditional JavaScript methods. Different Vue Directives The different Vue directives we use in this module are listed below. Example: The v-bind Directive Vue v-bind Directive You have already seen that a basic Vue setup consists of a Vue instance and that we can access it from the tag with {{ }} or the v-bind directive. On this page we will explain the v-bind directive in more detail. Vue v-bind Directive The v-bind directive lets us bind an HTML attribute to data in the Vue instance. This makes it easy to EXAMPLE change the attribute value The src attribute value of an tag is dynamically. taken from the Vue instance data property 'url': CSS Binding We can use the v-bind directive to do in-line styling and modify classes dynamically. We will show you briefly how to do that in this section, and later in this tutorial, on the CSS Binding page, we will explain this in more detail. CSS Binding (cont…) Bind style In-line styling with Vue is done by binding the style attribute to Vue with v-bind. As a value to the v-bind directive, we can write a JavaScript object with the CSS property and value: CSS Binding (cont…) Bind class We can use v-bind to change the class attribute. The value of v-bind:class can be a variable: CSS Binding (cont…) Bind class The value of v-bind:class can also be an object, where the class name will only take effect if it is set to 'true': CSS Binding (cont…) Shorthand for v-bind The shorthand for 'v-bind:' is simply ':'. Vue v-if Directive It is a lot easier to create an HTML element depending on a condition in Vue with the v-if directive than with plain JavaScript. Conditional Rendering in Vue Conditional rendering in Vue is done by using the v-if, v-else-if and v-else directives. Conditional rendering is when an HTML element is created only if a condition is true, i.e. create the text "In stock" if a variable is 'true', or 'Not in stock' if that variable is 'false'. Vue v-if Directive (cont…) Conditions in Vue A condition, or "if-statement", is something that is either true or false. A condition is often a comparison check between two values like in the example above to see if one value is greater than the other. We use comparison operators like = or !== to do such checks. Comparison checks can also be combined with logical operators such as && or ||. We can use the number of typewriters in storage with a comparison check to decide if they are in stock or not: Vue v-if Directive (cont…) Directives for Conditional Rendering This overview describes how the different Vue directives used for conditional rendering are used together. Vue v-if Directive (cont…) To see an example with all three directives shown above, we can expand the previous example with v-else-if so that the user sees 'In stock', 'Very few left!' or 'Out of stock': Vue v-if Directive (cont…) Use The Return Value from a Function Instead of using a comparison check with the v-if directive, we can use the 'true' or 'false' return value from a function: Vue v-if Directive (cont…) Vue v-show Directive Learn how to make an element visible or not with v-show. v-show is easy to use because the condition is written right in the HTML tag attribute. Conditional Visibility The v-show directive hides an element when the condition is 'false' by setting the CSS 'display' property value to 'none'. After writing v-show as an HTML attribute we must give a conditon to decide to have the tag visible or not. Vue v-show Directive (cont…) v-show vs. v-if The difference between v-show and v-if is that v-if creates (renders) the element depending on the condition, but with v-show the element is already created, v-show only changes its visibility. Therefore, it is better to use v-show when switching visibility of an object, because it is easier for the browser to do, and it can lead to a faster response and better user experience. Vue v-show Directive (cont…) Vue v-for Directive With Vue you start with the HTML element you want to create into a list, with v-for as an attribute, refer to the array inside the Vue instance, and let Vue take care of the rest. And the elements created with v-for will automatically update when the array changes. Vue v-for Directive (cont…) List Rendering List rendering in Vue is done by using the v-for directive, so that several HTML elements are created with a for-loop. Below are three slightly different examples where v-for is used. Vue v-for Directive (cont…) Loop Through an Array Loop through an array to display different images: Vue v-for Directive (cont…) Loop Through Array of Objects Loop through an array of objects and display the object properties: Vue v-for Directive (cont…) Get the index The index number of an array element can be really useful in JavaScript for-loops. Luckily we can get the index number when using v-for in Vue as well. To get the index number with v-for we need to give two comma separated words in parentheses: the first word will be the array element, and the second word will be the index of that array element. Vue v-for Directive (cont…) We can also display both array element index and information from the array element itself, if the array elements are objects: Vue Events Event handling in Vue is done with the v-on directive, so that we can make something happen when for example a button is clicked. Event handling is when HTML elements are set up to run a certain code when a certain event happens. Vue Events (cont…) Events in Vue are easy to use and will make our page truly responsive. Vue methods are code that can be set up to run when an event happens. With v-on modifiers you can describe in more detail how to react to an event. Get started with events Lets start with an example to show how we can click a button to count moose in a forest. We need: 1. A button 2. v-on on the tag to listen to the 'click' event 3. Code to increase the number of moose 4. A property (variable) in the Vue instance to hold the number of moose 5. Double curly braces {{}} to show the increased number of moose Events There are lots of events we can use as triggers for running code, among the most common ones are: 'click', 'mouseover', 'mouseout', 'keydown' and 'input'. 'v-on' The v-on directive allows us to create pages that respond to what the user does. The Vue v-on works by telling the browser what event to listen to, and what to do when that event occurs. Methods If we want to run more complex code when an event occurs we can put the code in a Vue method and refer to this method from the HTML attribute, like this: Event Modifiers In addition to v-on and Vue methods we can use something called event modifiers to modify an event so that it for example only happens once after a page is loaded, or modify an event like 'submit' to prevent a form from being submitted. Vue v-on Directive Like event handling in plain JavaScript, the v-on directive in Vue tells the browser: 1. which event to listen to ('click', 'keydown', 'mouseover', etc) 2. what to do when that event occurs Vue v-on Directive onclick Event The v-on directive allows us to perform actions based on specified events. Use v-on:click to perform action when the element is clicked. Vue v-on Directive oninput Event Use v-on:input to perform action when the element gets an input, like a keystroke inside a text field. Vue v-on Directive mousemove Event Use v-on:mousemove to perform action when the mouse pointer moves over an element. Vue v-on Directive Use v-on in a v-for Loop You can also use the v-on directive inside a v-for loop. The items of the array are available for each iteration inside the v-on value. Vue v-on Directive Shorthand for v-on The shorthand for 'v-on' is simply '@'. Vue Methods Vue methods are functions that belong to the Vue instance under the 'methods' property. Vue methods are great to use with event handling (v-on) to do more complex things. Vue methods can also be used to do other things than event handling. Vue Methods (cont…) There is another Vue property called 'methods' where we can store functions that belong to the Vue instance. A method can be stored in the Vue instance like this: Vue Methods (cont…) Example The v-on directive is used on the element to listen to the 'click' event. When the 'click' event occurs the 'writeText' method is called and the text is changed. Call a Method with the Event Object (cont…) When an event occurs so that a method is called, the event object is passed with the method by default. This is very convenient because the event object contains a lot of useful data, like for example the target object, the event type, or the mouse position when the 'click' or 'mousemove' event occurred. Vue Methods (cont…) Example The v-on directive is used on the element to listen to the 'mousemove' event. When the 'mousemove' event occurs the 'mousePos' method is called and the event object is sent with the method by default so we can get the mouse pointer position. We must use the this. prefix to refer to "xPos" inside the Vue instance data property from the method. Vue Methods (cont…) If we expand the example above by just one line, we can also make the background color change based on the mouse pointer position in the x-direction. The only thing we need to add is v-bind to change the background-color in the style attribute: Vue Methods (cont…) Example The v-on directive is used on the tag to listen to the 'input' event which occurs whenever there is a change in the text inside the textarea element. When the 'input' event occurs the 'writeText' method is called and the event object is sent with the method by default so we can get the text from the tag. The 'text' property in the Vue instance is updated by the 'writeText' method. A span element is set up to show the 'text' value with the double curly braces syntax, and this is updated automatically by Vue. Vue Methods (cont…) Passing Arguments Sometimes we want to pass an argument with the method when an event occurs. Lets say you work as a forest ranger, and you want to keep count of moose sightings. Vue Methods (cont…) Lets see how passing an argument with a method works in a full example Vue Event Modifiers Event modifiers in Vue modify how events trigger the running of methods and help us handle events in a more efficient and straightforward way. Vue Event Modifiers (cont..) Event modifiers are used together with the Vue v-on directive, to for example: Prevent the default submit behavior of HTML forms (v-on:submit.prevent ) Make sure that an event can only run once after the page is loaded (v-on:click.once ) Specify what keyboard key to use as an event to run a method (v-on:keyup.enter ) How To Modify The v-on Directive Event modifiers are used to define how to react on an event in more detail. We use event modifiers by first connecting a tag to an event like we have seen before: How To Modify The v-on Directive Example The.once modifier is used on the tag to only run the method the first time the 'click' event happens. Keyboard Key Event Modifiers We have three different keyboard event types keydown, keypress, and keyup. With each key event type, we can specify exactly what key to listen to after a key event occurs. We have.space,.enter,.w and.up to name a few. Keyboard Key Event Modifiers Example The keydown keyboard event triggers the 'getKey' method, and the value 'key' from the event object is written to the console and to the web page. Keyboard Key Event Modifiers We can also choose to limit the event to happen only when a mouse click or a key press happens in combination with system modifier keys.alt,.ctrl,.shift or.meta. The system modifier key.meta represents the Windows key on Windows computers, or command key on Apple computers. Keyboard Key Event Modifiers Combine Keyboard Event Modifiers Mouse Button Modifiers To react on a mouse click, we can write v-on:click, but to specify which mouse button that was clicked, we can use.left,.center or.right modifiers. Vue Forms Vue gives us an easy way to improve the user experience with forms by adding extra functionality like responsiveness and form validation. Vue uses the v-model directive when handling forms. Vue Forms Our First Form with Vue Let’s start with a simple shopping list example to see how Vue can be used when creating a form. Vue v-model Directive v-model creates a link between the input element value attribute and a data value in the Vue instance. When you change the input, the data updates and when the data changes, the input updates as well (two-way binding). Vue v-model Directive Two-way Binding As we have already seen in the shopping list example on the previous page, v-model provides us with a two-way binding, meaning that the form input elements update the Vue data instance, and a change in the Vue instance data updates the inputs. Vue v-model Directive Example Two-way binding: Try to write inside the input field to see that the Vue data property value gets updated. Try also to write directly in the code to change the Vue data property value, run the code, and see how the input field is updated. A Dynamic Checkbox We add a checkbox to our shopping list on the previous page to mark if an item is important or not. We use v-model to add this dynamic checkbox and text to improve user interaction. Vue Computed Properties - are like data properties, except they depend on other properties. - are written like methods, but they do not accept any input arguments. - are updated automatically when a dependency changes, while methods are called on when something happens, like with event handling for example. - are used when outputting something that depends on something else. Computed Properties are Dynamic The big advantage with a computed property is that it is dynamic, meaning it changes depending on for example the value of one or more data properties. Computed properties is the third configuration option in the Vue instance that we will learn. The first two configuration options we have already looked at are 'data' and 'methods'. Computed Properties are Dynamic As with 'data' and 'methods' computed properties also has a reserved name in the Vue instance: 'computed'. Computed Properties vs. Methods Computed properties and methods are both written as functions, but they are different: Methods runs when called from HTML, but computed properties updates automatically when a dependency change. Computed properties are used the same way we use data properties, but they are dynamic. Vue Watchers A watcher is a method that watches a data property with the same name. A watcher runs every time the data property value changes. Use a watcher if a certain data property value requires an action. The Watcher Concept Watchers is the fourth configuration option in the Vue instance that we will learn. The first three configuration options we have already looked at are 'data', 'methods' and 'computed'. As with 'data', 'methods' and 'computed' watchers also has a reserved name in the Vue instance: 'watch'. The Watcher Concept As mentioned in the green area at the top, a watcher monitors a data property with the same name. We never call a watcher method. It is only called automatically when the property value changes. The new property value is always available as an input argument to the watcher method, and so is the old value. The Watcher Concept Example An element is used to change a value 'rangeVal'. A watcher is used to prevent the user from choosing values between 20 and 60 that are considered illegal. Watchers vs. Methods Watchers and methods are both written as functions, but there are many differences: - Methods are called from HTML. - Methods are often called when an event happens. - Methods automatically receives the event object as an input. - Watchers are only called when the watched data property value changes, and this happens automatically. - Watchers automatically receives the new and old value from the watched property. Watchers vs. Computed Properties Watchers and computed properties are both written as functions. Watchers and computed properties are both called automatically when a dependency change, and never called from HTML. Watchers vs. Computed Properties Here are some differences between computed properties and watchers: - Watchers only depend on one property, the property they are set up to watch. - Computed properties can depend on many properties. - Computed properties are used like data properties, except they are dynamic. - Watchers are not referred to from HTML. Vue Templates A template in Vue is what we call the HTML part of our Vue application. The tag will later be used in *.vue files to structure our code in a better way. It is possible to use template as a configuration option in the Vue instance, and put the HTML code inside. The Vue Template The HTML content from inside the is moved to the configuration option 'template', encapsulated in backtick quotes `...`. We Let's look at an example can write many lines of HTML inside a backtick quote `...`. where we use 'template' as a configuration option. This is a simple example where we have just moved the HTML part into the configuration option 'template': Single File Components (SFCs) As you can see in the code example above, also the HTML part of our Vue application can be gathered inside the Vue instance, but this does not make it easier to get an overview in the HTML file. To get a better overview, to make it easier to handle larger projects, and to get a better development environment, we will now switch to write our Vue code in SFCs, or *.vue files. Single File Components (SFCs) All *.vue files only consist of three parts: - where the HTML content is. - for our Vue code. - where we write the CSS styling. But before we can use *.vue files in our project we need to set up our computer in a different way.