Categories
Vue 3

Vue 3 — v-for

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at rendering arrays and objects with v-for .

v-if with v-for

We shouldn’t use v-if and v-for together.

This is because v-for renders everything and then v-if checks every item whether they need to be rendered.

Instead, we should filter out the items beforehand with computed properties and use that with v-for .

When they’re used together, v-for has higher priority over v-if .

List Rendering

We can render an array of items onto the screen with v-for .

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div v-for="p in people">
        {{ p.name }}
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            people: [{ name: "mary" }, { name: "james" }, { name: "jane" }]
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

to render the items in the people array onto the screen.

We use the v-for directive to loop through each entry and render each item onto the screen.

We can also get the index of the item by writing:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg._com_/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div v-for="(p, index) in people">
        {{index}} - {{ p.name }}
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            people: [{ name: "mary" }, { name: "james" }, { name: "jane" }]
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

Then we get the index of the item with index.

We used in to loop through the array, but we can replace in with of to make it resemble the for-of loop:

<div v-for="p of people"></div>

v-for with an Object

v-for also works for objects.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div v-for="value in obj">
        {{value}}
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            obj: {
              james: 20,
              mary: 30,
              jane: 10
            }
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

to loop through the values of an object and display each value.

To get the key, we can add a second parameter to the loop:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div v-for="(value, name) in obj">
        {{name}}: {{value}}
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            obj: {
              james: 20,
              mary: 30,
              jane: 10
            }
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

name has the key of the object.

The 3rd item in the comma-separated list is the index:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div v-for="(value, name, index) in obj">
        {{index}} - {{name}}: {{value}}
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            obj: {
              james: 20,
              mary: 30,
              jane: 10
            }
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

Conclusion

We can render objects and arrays with the v-for directive.

Categories
Vue 3

Vue 3 — Inline Styles and v-if

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at inline style bindings and v-if.

Binding Inline Styles

There’re various ways to bind inline styles to an element.

One way is to pass in an object to the :style directive.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div :style="{ color, fontSize: `${fontSize}px` }">
        hello
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            color: "red",
            fontSize: 30
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

We have the color and fontSize properties in the object we return in the data method.

Then we used that in the object we use as the value of the :style directive.

So ‘hello’ should be red and 30px in size.

We can replace that with an object to make the template shorter.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div :style="styleObj">
        hello
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            styleObj: {
              color: "red",
              fontSize: "30px"
            }
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

There’s also an array syntax to let us add multiple style objects to the same element.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div :style="[baseStyles, overridingStyles]">
        hello
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            baseStyle: {
              color: "red",
              fontSize: "30px"
            },
            overridingStyles: {
              color: "green"
            }
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

We have the baseStyles and overridingStyles in one array.

The styles in overridingStyles will override the styles in baseStyle completely.

So we get that the text is green and it’s in its default size.

If browser-specific prefixes are needed, then they’ll be added automatically.

We can also provide an array of values to a style property with an array.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }">
        hello
      </div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {};
        }
      }).mount("#app");
    </script>
  </body>
</html>

We have all the variants of flex in the array.

Conditional Rendering

We can add conditional rendering with the v-if directive.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <button @click="on = !on">toggle</button>
      <h1 v-if="on">hello world!</h1>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            on: true
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

We have the on property returned with the object we return indata , so we can use it with v-if to conditionally render the h1 element.

Also, we have a button to toggle on between true or false so that we’ll see the h1 toggled on and off as we click the button.

Conclusion

Inline styles can be added with the :style directive.

It takes an object or an array.

We can use v-if to conditionally render an element.

Categories
Vue 3

Vue 3 — Event Handling

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at how to handle events in Vue 3 components.

Listening to Events

We can listen to events with the v-on directive, or @ for short.

For instance, we can listen to clicks by writing:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button v-on:click="onClick">click me</button>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        methods: {  
          onClick() {  
            alert("clicked");  
          }  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

We added the v-on:click directive to run the onClick method when we click the button.

So we should see an alert when we click the button.

To shorten it, we can write:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="onClick">click me</button>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        methods: {  
          onClick() {  
            alert("clicked");  
          }  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

We can put any JavaScript expression as the value of the v-on directive.

Methods in Inline Handlers

We don’t have to bind directly to the method in the expression we pass into v-on .

We can also call the method in there.

For example, we can write:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="onClick('hi')">hi</button>  
      <button @click="onClick('bye')">bye</button>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        methods: {  
          onClick(str) {  
            alert(str);  
          }  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

We pass in an argument to the onClick method so that onClick will get the argument and display the message.

To access the event object of the event, we can use the $event object.

For example, we can write:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="onClick('hi', $event)">click me</button>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        methods: {  
          onClick(str, event) {  
            event.stopPropagation();  
            alert(str);  
          }  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

to pass in the $event object to our event handler.

Then we can call stopPropagation on it to stop the click event from propagation to parent elements.

This event object is the native event object.

Multiple Event Handlers

We can have multiple event handlers in one expression.

For example, we can write:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="one($event), two($event)">click me</button>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        methods: {  
          one(event) {  
            console.log("one");  
          },  
          two(event) {  
            console.log("two");  
          }  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

to run one and two as event handlers when we click on the button.

Event Modifiers

We can add event modifiers so that we don’t have to call methods like event.preventDefault() or event.stopPropagation() in our event handlers.

The modifiers include:

  • .stop
  • .prevent
  • .capture
  • .self
  • .once
  • .passive

These are added to the v-on directive.

For example, to call event.stopPropagation in our event handler, we can write:

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

then the click event won’t be propagated to the parent elements.

And if we write:

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

event.preventDefault() will be called when running onSubmit .

Modifiers can also be chained, so we can write:

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

The capture modifier lets us use capture mode when adding an event listener.

And the self modifier only triggers the event handler if the event.target is the element itself.

once will only trigger the event handler at most once.

The passive modifier corresponds to the addEventListener ‘s passive option.

If we add it to the @scroll directive:

<div @scroll.passive="onScroll">...</div>

then the scroll event’s default behavior will happen immediately instead of waiting for onScroll to complete.

passive and prevent shouldn’t be used together since prevent will be ignored.

passive communicates to the browser that we don’t want to prevent the default browser behavior.

Conclusion

We can listen to events with the v-on directives.

It makes many arguments and modifiers.

Categories
Vue 3

Vue 3 — Conditional Rendering

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at conditionally rendering items with Vue.

v-else

We can use v-else to display an alternative item with the value in v-if is falsy.

For example, we can write:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="on = !on">toggle</button>  
      <h1 v-if="on">hello</h1>  
      <h1 v-else>bye</h1>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        data() {  
          return {  
            on: true  
          };  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

When we toggle on to true , the ‘hello’ is displayed.

Otherwise, ‘bye’ is displayed.

v-else must immediately follow a v-if or a v-else-if element.

Otherwise, it won’t be recognized.

Conditional Groups with v-if on <template>

v-if can be used on template so that we can conditionally display a group of elements.

For example, we can write:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="on = !on">toggle</button>  
      <template v-if="on">  
        <h1>Title</h1>  
        <p>Paragraph 1</p>  
        <p>Paragraph 2</p>  
      </template>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        data() {  
          return {  
            on: true  
          };  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

We have the v-if added to the template so that we can toggle everything inside all at once.

v-else-if

We can use v-else-if to display something if a case is true .

For example, we can write:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <div v-if="type === 'a'">  
        a  
      </div>  
      <div v-else-if="type === 'b'">  
        b  
      </div>  
      <div v-else-if="type === 'c'">  
        c  
      </div>  
      <div v-else>  
        something else  
      </div>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        data() {  
          return {  
            type: "a"  
          };  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

We have the v-else-if directive to display the different items according to the value of type .

Since we set it to 'a' , we’ll see ‘a’ displayed.

v-else-if must be immediately after v-if or another v-else-if element.

v-show

The v-show directive also lets us conditionally rendering items on the screen.

But the difference is that v-show elements always render on the DOM and it’s hidden with CSS if its value is falsy.

v-show doesn’t support the template element and can’t be used with v-else .

For example, we can use it by writing:

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://unpkg.com/vue@next"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="on = !on">toggle</button>  
      <h1 v-show="on">hello</h1>  
    </div>  
    <script>  
      const vm = Vue.createApp({  
        data() {  
          return {  
            on: true  
          };  
        }  
      }).mount("#app");  
    </script>  
  </body>  
</html>

We have the v-show directive which will toggle the CSS display property to show or hide the h1 element.

v-if vs v-show

v-if is real conditional rendering because all the event listeners and child components are destroyed when they aren’t rendered.

v-if is lazy, so if its value is falsy, it won’t be rendered until it becomes true .

v-show is much simpler, it just toggles the display CSS property to change the display.

v-show is better if we need to toggle something often and v-if is good for other cases.

Conclusion

We can use v-if and v-show to conditionally render items.

v-if changes the DOM structure, and v-show changes the CSS only.

Categories
Vue 3

Vue 3 — HTML and Directives

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at how to create templates with Vue 3.

Raw HTML

We can render raw HTML with the v-html directive.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <p>{{ rawHtml }}</p>
      <p><span v-html="rawHtml"></span></p>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            rawHtml: `<b>foo</b>`
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

We have the rawHtml property returned with the object we return in the data method.

If we pass raw HTML into the mustache, it’ll be sanitized. This means the raw code will be displayed.

If we pass it into the v-html directive, it’ll be displayed as HTML, so it’ll be bold.

Therefore, if we use v-html , we should be careful of cross-site scripting vulnerabilities.

We should only display trusted content with v-html .

Attributes

If we want to set attribute values dynamically, we’ve to use the v-bind directive.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <div v-bind:id="dynamicId"></div>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            dynamicId: `foo`
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

to set the id attribute of the div to foo by using v-bind .

If we have boolean attributes, its existence means we set the value totrue .

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <button v-bind:disabled="disabled">Button</button>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            disabled: true
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

We disabled the button by passing in the disabled value to v-bind:disabled , which is true .

JavaScript Expressions

We can put JavaScript expressions between the double curly braces.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      {{message.split('').reverse().join('')}}
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            message: "hello world"
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

to reverse 'hello world' in the template.

We can only put in single expressions and not statements, so we can’t write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      {{ var a = 1 }}}
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            message: "hello world"
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

The Vue template compiler will give us an error.

Directives

Directives are special attributes that starts with v- .

The values they expect are single JavaScript expressions.

v-for and v-on are exceptions to this.

We reactively apply the side effects to the DOM when the value of its expression changes.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <p v-if="show">hello world</p>
    </div>
    <script>
      const vm = Vue.createApp({
        data() {
          return {
            show: true
          };
        }
      }).mount("#app");
    </script>
  </body>
</html>

to show the ‘hello world’ message with v-if since show is true .

v-if is a directive that shows something when its value is truthy.

Conclusion

Templates can have raw HTML, attributes, and directives.

Directives are special attributes that take values.