vue

How to quickly detect the hover event in Vue.js

To detect mouse hover in Vue.js, use a hover state variable and the mouseenter & mouseleave events to detect when the mouse enters and leaves the element’s bounds.

App.vue
<template> <div @mouseenter="hover = true" @mouseleave="hover = false"></div> </template> <script> export default { data() { return { hover: false, }; }, }; </script>

The mouseenter event runs when the mouse pointer enters the bounds of an element, while mouseleave runs when it leaves.

We could also listen to the mouseover event to detect hover, this event runs for an element and every single one of its ancestor elements in the DOM tree (i.e. it bubbles) and this could cause serious performance problems in deep hierarchies. mouseenter doesn’t bubble so we can use it without worrying about this.

Change style on hover in Vue.js

To change the style of an element on hover in Vue.js, we can combine the hover state variable and the :class directive:

App.vue
<template> <div @mouseenter="hover = true" @mouseleave="hover = false" class="div" :class="{ 'div-hover': hover }" ></div> </template> <script> export default { data() { return { hover: false, }; }, }; </script> <style> .div { background-color: blue; width: 200px; height: 100px; } .div-hover { background-color: yellow; } </style>
Changing color on mouse hover in Vue.js.

Display another element on hover in Vue.js

We could also display another element in the UI when we detect hover. For example: a tooltip to display more info on a particular UI element.

To do this, you can pass the state variable to a v-if state directive you set on the element. This ensures that the element only displays when the hover state is true.

App.vue
<template> <button @mouseenter="hover = true" @mouseleave="hover = false" class="div" :class="{ 'div-hover': hover }" > Button </button> <p v-if="hover">Tooltip</p> </template> <script> export default { data() { return { hover: false, }; }, }; </script>
Displaying another element on hover.

Detect hover on Vue component

You can also use the mouseenter and mouseleave approach to detect hover on a custom Vue component.

components/StyledButton.vue
<template> <div> <button>Styled button</button> </div> </template> <style> button { height: 30px; width: 100px; background-color: lightgreen; } </style>
App.vue
<template> <styled-button @mouseenter="hover = true" @mouseleave="hover = false" ></styled-button> <p v-if="hover">Tooltip</p> </template> <script> import StyledButton from './components/StyledButton.vue'; export default { components: { StyledButton, }, data() { return { hover: false, }; }, }; </script>
Detecting mouse hover on a Vue.js custom component.

If you’re using Vue 2.x, you’ll need to use the .native event modifier to listen for native DOM events on the Vue component:

Vue
<styled-button @mouseenter.native="hover = true" @mouseleave.native="hover = false" ></styled-button>

Key takeaways

  • Detect mouse hover in Vue.js using a hover state variable and mouseenter & mouseleave events.
  • mouseover event can cause performance issues in deep hierarchies, mouseenter is safer.
  • Use hover state to conditionally apply CSS classes, changing element appearance on hover.
  • Use hover state with v-if to conditionally display elements like tooltips on hover.
  • mouseenter and mouseleave can detect hover on custom Vue components. Use .native modifier in Vue 2.x.

How to prevent form submission in Vue.js

To prevent a page refresh on form submit in Vue.js, use the .prevent event modifier in the submit event listener.

App.vue
<template> <div id="app"> <form @submit.prevent="handleSubmit"> <label> Email <br /> <input type="email" v-model="email" required /> </label> <br /> <label> Password <br /> <input type="password" v-model="password" required /> </label> <br /> <button type="submit" style="margin-top: 16px" > Submit </button> </form> </div> </template> <script> export default { name: 'App', data() { return { email: '', password: '', }; }, methods: { handleSubmit() { this.email = ''; this.password = ''; alert('Form submitted'); }, }, }; </script>
The page refresh is prevented in Vue.js when the button submits the form.

We use the .prevent modifier to stop the default action of the event from happening. In this case, that action was a page refresh, so .prevent stopped the page refresh on the form submission.

App.vue
<form @submit.prevent="handleSubmit">

.prevent is a Vue.js event modifier, which lets us access and modify event-related data.

We use the @submit directive to add a submit event listener to the form; this listener runs when the user clicks the button to submit the form.

In this case we only reset the form; in practical scenarios you’ll likely make an AJAX request to a server with the form data.

App.vue
<template> ... </template> <script> export default { ... methods: { async handleSubmit() { const user = { email: this.email, password: this.password, }; try { const response = await axios.post('http://your-api-url.com', user); console.log(response.data); } catch (error) { console.error(error); } this.email = ''; this.password = ''; } } }; </script>

For the button to submit the form, we must set its type attribute to "submit"

App.vue
<button type="submit" style="margin-top: 16px;"> Submit </button>

With type="submit", the browser also submits the form when the user presses the Enter key in an input field.

Remove type="submit" from the button to prevent page refresh

To prevent page refresh on form submit in Vue.js, you can also remove the type="submit" from the button.

When is this useful? You may want to show an alert message or something before submission. In this case, we wouldn’t want type="submit" since it submits the form on button click.

App.vue
<template> <div id="app"> <form> <label> Email <br /> <input type="email" v-model="email" required /> </label> <br /> <label> Password <br /> <input type="password" v-model="password" required /> </label> <br /> <button type="button" @click="handleSubmit" style="margin-top: 16px" > Submit </button> </form> </div> </template> <script> export default { data() { return { email: '', password: '', }; }, methods: { handleSubmit() { // Perform custom actions before form submission alert('Are you sure you want to submit the form?'); // Simulate form submission by clearing input fields this.email = ''; this.password = ''; alert('Form submitted'); }, }, }; </script>
Preventing a page refresh on form submit in Vue.js to show an alert dialog before submission.

We used type="button" on the button, but that’s as good as not having a type attribute. It doesn’t do anything on click.

Key takeaways

  • To prevent page refresh on form submit in Vue.js, use the .prevent modifier in the submit event listener.
  • Set type="submit" to ensure the form submits on button click or Enter press. Remove it when you don’t want this.
  • Remove type="submit" when something needs to happen after the button click before submitting the form, e.g., show a dialog, make an initial request, etc.

How to Scroll to the Top of a Page in Vue.js

To scroll to the top of a page in Vue.js, call window.scrollTo({ top: 0, left: 0}).

App.vue
<template> <div> <h2>Top of the page</h2> <div style="height: 100rem" /> <div ref="listOfCities"> <h2 v-for="city in allCities" :key="city">{{city}}</h2> </div> <button @click="scrollToTop">Scroll to top</button> <div style="height: 150rem" /> </div> </template> <script> export default { data() { return { allCities: [ 'Tokyo', 'New York City', 'Paris', 'London', 'Dubai', 'Sydney', 'Rio de Janeiro', 'Cairo', 'Singapore', 'Mumbai', ], }; }, methods: { scrollToTop() { window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); }, }, }; </script>
Clicking the button to scroll to the top of the page in Vue.js

The window.scrollTo() method scrolls to a particular position on a page.

We could have called it with two arguments: window.scrollTo(0, 0).

But this overload of scrollTo() doesn’t let us set a smooth scroll behavior.

When behavior is smooth, the browser scrolls to the top of the page in a gradual animation.

But when it’s auto, the scroll happens instantly. We immediately jump to the top of the page.

We use the @click directive of the button to set a click listener.

This listener will get called when the user clicks the button.

Scroll to bottom of page in Vue.js

We use a different approach to scroll to the end of the page in Vue.js.

We create an element at the end of the page.

We set a ref on it.

Then we scroll to it by calling scrollIntoView() on the ref.

App.vue
<template> <div> <h2>Top of the page</h2> <button @click="scrollToBottom">Scroll to bottom</button> <div style="height: 100rem" /> <div> <h2 v-for="city in allCities" :key="city">{{city}}</h2> </div> <div style="height: 150rem" /> <div ref="bottomElement"></div> <h2>Bottom of the page</h2> </div> </template> <script> export default { data() { return { allCities: [ 'Tokyo', 'New York City', 'Paris', 'London', 'Dubai', 'Sydney', 'Rio de Janeiro', 'Cairo', 'Singapore', 'Mumbai', ], }; }, methods: { scrollToBottom() { this.$refs.bottomElement.scrollIntoView({ behavior: 'smooth' }); }, }, }; </script>
Clicking the button to scroll to the bottom of the page in Vue.js

scrollIntoView() scrolls to a specific element on the page.

By calling it on the bottom element, we scroll to the page end.

Like scrollTo(), scrollIntoView() has a behavior option that controls the scrolling motion.

App.vue
scrollToBottom() { this.$refs.bottomElement?.scrollIntoView({ behavior: 'smooth' }); }

smooth scrolls to the element in an animation.

auto jumps to the element on the page instantly. It’s the default.

To access the bottom element, we set a Vue ref on it.

To do this, we create a ref object and set the element’s ref prop to it.

App.vue
<template> <div ref="bottomElement"></div> </template>

Doing this lets us access the element’s HTMLElement object with this.$refs.bottomElement.

Vue refs are a way to register a reference to an element or a child component.

The registered reference will be updated whenever the component re-renders.

Key takeaways

  • In Vue.js, to scroll to the top of a page, call window.scrollTo() with { top: 0, left: 0, behavior: 'smooth' }.
  • Setting behavior to 'smooth' makes a gradual animated scroll to the top.
    'auto' causes an instant jump to the top.
  • To scroll to the bottom of a page in Vue.js, call scrollIntoView() on a specific element.
    Create a ref for it using the ref attribute first.
  • Vue refs are used to create a reference to an element.
    This allows access to its properties during the component’s lifecycle.

How to to Scroll to an Element in Vue.js

To scroll to an element in Vue.js:

  1. Set a ref on the target element.
  2. Call scrollIntoView() on the target ref.
HTML
// Set ref on target element <div ref="targetRef" style="background-color: lightblue;"> My Target Element </div>
JavaScript
// Scroll to element this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' });

We can use this approach to scroll to an element when another trigger element is clicked.

We’ll first need to set a click event listener on the trigger element.

Then we’ll call scrollIntoView() in the listener.

App.vue
<template> <div id="app"> <button @click="handleClick">Scroll to element</button> <div style="height: 150rem;"></div> <div ref="targetRef" style="background-color: lightblue;"> Coding Beauty </div> <div style="height: 150rem;"></div> </div> </template> <script> export default { data() { return { ref: null }; }, methods: { handleClick() { this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' }); } } }; </script>
Using the button to scroll down to an element in Vue.js.

Scrolling on click is great for quick navigation.

It improves the user experience.

It’s great for long lists and pages with many sections.

It makes apps more interactive with smooth-scrolling animations.

We set the ref prop of the target element to create a Vue ref.

Doing this lets us access the component’s HTML element directly from the $refs instance property.

We use the @click event to set an event listener that will be called when the trigger element is clicked.

App.vue
<button @click="handleClick">Scroll to element</button>
App.vue
methods: { handleClick() { this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' }); } }

We can use this same combo of refs and scrollIntoView() to scroll to an element in React.

In the click listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto.

auto is the default.

Scroll to dynamic element on click in Vue.js

We can do something similar to scroll to a dynamically created element in Vue.js:

App.vue
<template> <div id="app"> <div style=" position: fixed; background-color: white; bottom: 0; margin-bottom: 10px; " > <button @click="addFruit">Add fruit</button> <button @click="scrollToLastFruit" style="margin-left: 8px" > Scroll to last </button> </div> <div style="height: 5rem"></div> <div ref="fruitList"> <h2 v-for="fruit in fruits" :key="fruit" > {{ fruit }} </h2> </div> <div style="height: 150rem"></div> </div> </template> <script> const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default { data() { return { fruits: allFruits.slice(0, 3), }; }, methods: { addFruit() { this.fruits.push(allFruits[this.fruits.length]); }, scrollToLastFruit() { const lastChildElement = this.$refs.fruitList.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to a dynamic element in Vue.js.

Here we have a list of fruits displayed.

The Add fruit button dynamically adds an item to the fruit list on click.

Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the @click event to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant.

Doing this sets the Vue instance’s $refs.inputList property to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

App.vue
methods: { addFruit() { this.fruits.push(allFruits[this.fruits.length]); }, scrollToLastFruit() { const lastChildElement = this.$refs.fruitList.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, },

Scroll to element after render in Vue.js

To scroll to an element after render in Vue.js:

  1. Set a ref on the element
  2. Create a mounted lifecycle hook to run code just after the component mounts.
  3. Call scrollIntoView() on the ref object in the mounted hook.
App.vue
<template> <div> <div style="height: 150rem"></div> <div ref="target" style="background-color: blue; color: white" > Coding Beauty </div> <div style="height: 150rem"></div> </div> </template> <script> export default { mounted() { this.scrollToElement(); }, methods: { scrollToElement() { this.$refs.target.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to an element after render in Vue.js

Scrolling after page loads help users find info.

It also helps fix errors.

It’s great for those who use special software.

It makes browsing the webpage easier.

We create a Vue ref by setting the target element’s ref prop to a string ("target")

We’ll then be able to access the HTMLElement object representing this object from the $refs property of the Vue instance (this.$refs.target).

The mounted method is a Vue lifecycle hook that runs just after the component has mounted. This is similar to useEffect in React.

In mounted, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame (auto).

auto is the default.

Key takeaways

  • To scroll to an element in Vue, set a ref on the target element and call scrollIntoView() on the ref.
  • To scroll to a dynamically created element in Vue.js, set the ref on the list element and use lastElementChild to scroll to its last item.
  • To scroll to an element after render in Vue.js, create a mounted lifecycle hook and call scrollIntoView() on the ref object in the mounted hook.

How to Get the Current Year in Vue.js

To get the current year in Vue.js, create a new Date object with the Date() constructor, then use the getFullYear() method to get the year of the Date. getFullYear() will return a number that represents the current year.

For example:

App.vue
<template> <div> {{ new Date().getFullYear() }} <div> &copy; {{ new Date().getFullYear() }} Coding Beauty </div> </div> </template>
The current year is displayed.
The current year is displayed.

We use the Date() constructor to create a new Date object. When Date() is called with no arguments, the Date object is created using the current date and time.

The Date getFullYear() method returns a number that represents the year of the Date. Since the Date object here stores the current date, getFullYear() returns the current year.

Get current year with data property

We can also put the current year in a data variable instead of placing it directly in the template with the {{ }} symbols. This allows us to more easily reuse the value in multiple places in the template markup.

App.vue
<template> <div> {{ currYear }} <div>&copy; {{ currYear }} Coding Beauty</div> </div> </template> <script> export default { data() { return { currYear: new Date().getFullYear(), }; }, }; </script>

Get current year with Composition API

Of course, this also works when using the Vue 3 Composition API:

App.vue
<script setup> const currYear = new Date().getFullYear(); </script> <template> <div> {{ currYear }} <div>&copy; {{ currYear }} Coding Beauty</div> </div> </template>

Get current month

If you also want to get the current month, the getMonth() method is for you.

getMonth() returns a zero-based index that represents the month of the Date. Zero-based here means that 0 = January, 1 = February, 2 = March, etc.

App.vue
<template> <div>Month number {{ currMonth }} in {{ currYear }}</div> </template> <script> export default { data() { return { currMonth: new Date().getMonth(), currYear: new Date().getFullYear(), }; }, }; </script>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getmonth
The month number is displayed.

If you want the month name directly (the more likely case), the Date toLocaleString() method will do the job.

App.vue
<template> <div>{{ currMonth }} in {{ currYear }}</div> </template> <script> export default { data() { return { currMonth: new Date().toLocaleString([], { month: 'long', }), currYear: new Date().getFullYear(), }; }, }; </script>
The month name is displayed.

Check out this article for a full guide on how to convert a month number to its equivalent month name in JavaScript.

Get current day of month

Similarly, to get the current day in the month, you’d use the Date getDate() method:

App.vue
<template> <div>{{ currMonth }} {{ currDay }}, {{ currYear }}</div> </template> <script> export default { data() { return { currDay: new Date().getDate(), currMonth: new Date().toLocaleString([], { month: 'long', }), currYear: new Date().getFullYear(), }; }, }; </script>
The current day of the month is displayed.
The current day of the month is displayed.

Get current year, month, day, week…

While you could get each component of the date using different functions, a much more flexible and easy way to do this is by formatting the date in the given format with a format specifier.

We can carry out this formatting with the format() function from the date-fns library.

In the following example, we use date-fns format() to get the multiple individual parts of the date.

App.vue
<template> <div>{{ dateString }}</div> </template> <script> import { format } from 'date-fns'; export default { data() { return { dateString: format( new Date(), "EEEE, 'the' do 'of' LLLL, yyyy" ), }; }, computed() { return {}; }, }; </script>
Different parts of the date are displayed using formatting.
Different parts of the date are displayed using formatting.

The format() function takes a pattern and returns a formatted date string in the format specified by the pattern. You can find a list of the patterns format() accepts here.

For our example, we use the following patterns:

  • EEEE: to get the full name of the day of the week.
  • do: to get the ordinal day of the month, i.e., 1st, 2nd, 3rd, etc.
  • LLLL: to get the full name of the month of the year.
  • yyyy: to get the full year.

We also use single quotes to escape strings (the and of) that are not patterns but should be included in the result of the formatting.

How to Easily Handle the onScroll Event in Vue

To handle the onScroll event on a Vue element, assign a function to the scroll event of the element and use the event object the function receives to perform an action. The action will occur whenever the user scrolls up or down on the page.

For example:

App.vue
<template> <div id="app"> Scroll top: <b>{{ scrollTop }}</b> <br /> <br /> <div id="box" @scroll="handleScroll" > <p v-for="i in 10" :key="i" > Content </p> </div> </div> </template> <script> export default { data() { return { scrollTop: 0, }; }, methods: { handleScroll(event) { this.scrollTop = event.currentTarget.scrollTop; }, }, }; </script> <style scoped> #box { border: 1px solid black; width: 400px; height: 200px; overflow: auto; } </style>
The text is update when the componet's onScroll event fires.
The text is updated when the component’s onScroll event fires.

We use the @ character to set a listener for an event on the component.

Vue
<div id="box" @scroll="handleScroll" > <!-- ... --> </div>

The @ character is a shorter alternative to v-on:

Vue
<div id="box" v-on:scroll="handleScroll" > <!-- ... --> </div>

The function (event handler) passed to the scroll event is invoked whenever the viewport is scrolled. It is called with an event object, which you can use to perform actions and access information related to the scroll event.

The currentTarget property of this event object returns the element that the scroll listener was attached to.

Apart from detecting scroll events, we can also scroll to the element in Vue.js.

Tip: If you’re not sure of when to use the event object’s currentTarget or target properties, this article might help: Event target vs currentTarget in JavaScript: The Important Difference.

We use the element’s scrollTop property to get how far the element’s scrollbar is from its topmost position. Then we update the state variable with the new value, and this reflects on the page.

Handle onScroll event on window object

We can also handle the onScroll event on the global window object, to perform an action when the viewport is scrolled.

The addEventListener() method lets us do this:

JavaScript
<template> <div id="app"> Scroll top: <b>{{ scrollTop }}</b> <br /> <br /> <div id="label">Scroll top: {{ scrollTop }}</div> <div> <p v-for="i in 30" :key="i" > Content </p> </div> </div> </template> <script> export default { data() { return { scrollTop: 0, }; }, methods: { handleScroll() { this.scrollTop = window.scrollY; }, }, mounted() { window.addEventListener('scroll', this.handleScroll); }, beforeUnmount() { window.removeEventListener('scroll', this.handleScroll); }, }; </script> <style scoped> #label { position: fixed; padding: 10px 0; top: 0; background-color: white; border-bottom: 1px solid #c0c0c0; width: 100%; } </style>
The text is updated when the window’s onScroll event fires.
The text is updated when the window’s onScroll event fires.

The addEventListener() method takes up to two arguments:

  1. type: a string representing the event type to listen for, e.g., 'click', 'keydown', 'scroll', etc.
  2. listener: the function called when the event fires.

It also has some optional parameters, which you can learn more about here.

We call addEventListener() in the mounted hook to register the listener once the component renders as the page loads. mounted is only called for a component when it has been added to the DOM, so the listener will not be registered multiple times.

We also called the removeEventListener() method to unregister the event listener and prevent a memory leak. We place the call in the beforeUnmount hook so that it happens just before the component is removed from the DOM.

How to Capitalize the First Letter of a String in Vue.js

To capitalize the first letter of a string in Vue:

  1. Get the string’s first letter with [0].
  2. Uppercase this letter with .toUpperCase().
  3. Get the rest of the string with .slice(1).
  4. Add the results together.

For example:

App.vue

<template>
  <div id="app">
    <b>{{ name1 }}</b>
    <br />
    Capitalized: <b>{{ capitalized(name1) }}</b>
    <br /><br />
    <b>{{ name2 }}</b
>
    <br />
    Capitalized:
    <b>{{ capitalized(name2) }}</b>
  </div>
</template>

<script>
export default {
  data() {
    return { name1: 'coding beauty', name2: 'javascript' };
  },
  methods: {
    capitalized(name) {
      const capitalizedFirst = name[0].toUpperCase();
      const rest = name.slice(1);

      return capitalizedFirst + rest;
    },
  },
};
</script>
The strings and their capitalized forms.
The strings and their capitalized forms.

We create a reusable Vue instance method (capitalized) that takes a string and capitalizes its first letter.

We use bracket indexing ([ ]) to get the 0 property of the string – the character at index 0. String (and array) indexing is zero-based in JavaScript, so the string’s first character is at index 0, the second is at index 1, and so on, until the last character at index str.length-1.

After getting the string’s first character, we uppercase it with the toUpperCase() method.

We use the slice() method to get the rest of the string. slice() returns the portion of a string between a specified start and an optional end index. If the end index is omitted, the substring will range from the start index to the end of the string.

Hence, slice(1) returns a substring ranging from the second character to the end.

After getting the remaining part of the string, all that’s left is simply concatenating it with the capitalized first letter.

If it’s necessary for the resulting string to have only its first letter capitalized, you can call the toLowerCase() method on the result of slice(), to lowercase the rest of the string before concatenation.

const capitalizedFirst = name[0].toUpperCase();

// 👇 toLowerCase()
const rest = name.slice(1).toLowerCase();

return capitalizedFirst + rest;

Use Computed Property

If you’re trying to capitalize a string data property of the Vue instance (like in our example), you can use a computed property in place of a method.

<template>
  <div id="app">
    <b>{{ name1 }}</b>
    <br />
    Capitalized: <b>{{ capitalizedName1 }}</b> <br /><br />
    <b>{{ name2 }}</b
    ><br />
    Capitalized:
    <b>{{ capitalizedName2 }}</b>
  </div>
</template>

<script>
export default {
  data() {
    return { name1: 'coding beauty', name2: 'javascript' };
  },
  methods: {
    capitalized(name) {
      const capitalizedFirst = name[0].toUpperCase();
      const rest = name.slice(1);

      return capitalizedFirst + rest;
    },
  },

  // 👇 Computed properties
  computed: {
    capitalizedName1() {
      return this.capitalized(this.name1);
    },
    capitalizedName2() {
      return this.capitalized(this.name2);
    },
  },
};
</script>

Using a computed property for this is useful when the data is likely to change in the app’s lifetime, e.g., in a two-way binding with an input field. When the data property changes, the depending computed property will be recalculated and updated automatically.

How to Check if a Checkbox is Checked in Vue.js

To check if a checkbox is checked in Vue:

  1. Create a boolean state variable to store the value of the checkbox.
  2. Use v-model to set up a two-way binding between the checkbox’s value and the state variable.
  3. If the checkbox is checked, the state variable will be true. Otherwise, it will be false.

For example:

App.vue

<template>
  <div id="app">
    <input
      type="checkbox"
      v-model="agreement"
      name="agreement"
    />

    <label for="agreement">
      I agree to the terms and conditions
    </label>

    <br /><br />

    <button :disabled="!agreement">Continue</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      agreement: false,
    };
  },
};
</script>
The button is disabled when the checkbox is checked, and enabled when it is unchecked.
The button is disabled when the checkbox is checked, and enabled when it is unchecked.

The checked property of the checkbox object indicates whether or not the checkbox is checked.

Every time the checkbox is checked or unchecked, the agreement state variable will be automatically updated to true or false respectively.

We set the button‘s disabled prop to the negation of agreement to disable and enable it when agreement is true and false respectively.

Check if checkbox is checked with ref

In most cases, v-model will be sufficient for checking if a checkbox if a checked in Vue. However, we can also use the ref attribute to get the input value. We can set this attribute on any DOM element and use the $refs property of the Vue instance to access the object that represents the element.

For example:

<template>
  <div id="app">
    <!-- 👇 Set "ref" prop to create new ref -->
    <input
      type="checkbox"
      name="js"
      ref="theCheckbox"
    />

    <label for="js"> JavaScript </label>
    <br />
    <button @click="handleClick">Done</button>
    <p v-if="message">{{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return { message: '' };
  },
  methods: {
    handleClick() {
      // 👇 Access ref with "$refs" property
      if (this.$refs.theCheckbox.checked) {
        this.message = 'You know JS';
      } else {
        this.message = "You don't know JS";
      }
    },
  },
};
</script>
The checked state of the checkbox determines the message displayed when the button is clicked.
The checked state of the checkbox determines the message displayed when the button is clicked.

We set an onClick listener on the button. In this listener, we access the checkbox object using the ref, and use its checked property to determine the message that should be shown to the user when the button is clicked.

How to Change the Style of an Element on Click in Vue

To change the style of an element on click in Vue:

  1. Create a boolean state variable to conditionally set the style on the element depending on the value of this variable.
  2. Set a click event handler on the element that toggles the value of the state variable.

For example:

App.vue

<template>
  <div id="app">
    <p>Click the button to change its color.</p>

    <button
      role="link"
      @click="handleClick"
      class="btn"
      :style="{
        backgroundColor: active ? 'white' : 'blue',
        color: active ? 'black' : 'white',
      }"
    >
      Click
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: false,
    };
  },
  methods: {
    handleClick() {
      this.active = !this.active;
    },
  },
};
</script>

<style>
.btn {
  border: 1px solid gray;
  padding: 8px 16px;
  border-radius: 5px;
  font-family: 'Segoe UI';
  font-weight: bold;
}
</style>
Clicking the element changes its stye.
Clicking the element changes its style.

The active state variable determines the style that will be applied to the element. When it is false (the default), a certain style is applied.

We set a click event handler on the element, so that the handler will get called when it is clicked. The first time this handler is called, the active variable gets toggled to true, which changes the style of the element.

Note

To prevent the style from changing every time the element is clicked, we can set the state variable to true, instead of toggling it:

handleClick() {
  this.active = true

  // this.active = !this.active
},

We used ternary operators to conditionally set the backgroundColor and color style on the element.

The ternary operator works like an if/else statement. It returns the value before the ? if it is truthy. Otherwise, it returns the value to the left of the :.

const treshold = 10;

const num = 11;

const result = num > treshold ? 'Greater' : 'Lesser';

console.log(result) // Greater

So if the active variable is true, the backgroundColor and color are set to white and black respectively. Otherwise, they’re set to blue and white respectively.

Change element style on click with classes

To change the style of an element on click in Vue, we can also create classes containing the alternate styles and conditionally set them to the class prop of the element, depending on the value of the boolean state variable.

For example:

App.vue

<template>
  <div id="app">
    <p>Click the button to change its color.</p>

    <button
      role="link"
      @click="handleClick"
      class="btn"
      :class="active ? 'active' : 'non-active'"
    >
      Click
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: false,
    };
  },
  methods: {
    handleClick() {
      this.active = !this.active;
    },
  },
};
</script>

<style>
.btn {
  border: 1px solid gray;
  padding: 8px 16px;
  border-radius: 5px;
  font-family: 'Segoe UI';
  font-weight: bold;
}

.active {
  background-color: white;
  color: black;
}

.non-active {
  background-color: blue;
  color: white;
}
</style>

We create two classes (active and non-active) with different styles, then we use the ternary operator to add the active class if the active variable is true, and add the non-active class if otherwise.

The advantage of using classes is that we get to cleanly separate the styles from the template markup. Also, we only need to use one ternary operator.

Change element style on click with event.currentTarget.classList

There are other ways to change the style of an element in Vue without using a state variable.

With classes defined, we can use the currentTarget.classList property of the Event object passed to the click event handler to change the style of the element.

For example:

App.vue

<template>
  <div id="app">
    <p>Click the button to change its color.</p>

    <button
      role="link"
      @click="handleClick"
      class="btn non-active"
    >
      Click
    </button>
  </div>
</template>

<script>
export default {

  methods: {
    handleClick(event) {
      // 👇 Change style
      event.currentTarget.classList.remove('non-active');
      event.currentTarget.classList.add('active');
    },
  },
};
</script>

<style>
.btn {
  border: 1px solid gray;
  padding: 8px 16px;
  font-family: Arial;
  font-size: 1.1em;
  box-shadow: 0 2px 5px #c0c0c0;
}

.active {
  background-color: white;
  color: black;
}

.non-active {
  background-color: rebeccapurple;
  color: white;
}
</style>
Clicking the element changes its style.
Clicking the element changes its style.

We don’t use a state variable this time, so we add the non-active class to the element, to customize its default appearance.

The click event listener receives an Event object used to access information and perform actions related to the click event.

The currentTarget property of this object returns the element that was clicked and had the event listener attached.

We call the classList.remove() method on the element to remove the non-active class, then we call the classList.add() method on it to add the active class.

Notice that the style of the element didn’t change anymore after being clicked once. If you want to toggle the style whenever it is clicked, you can use the toggle() class of the element to alternate the classes on the element.

App.vue

<template>
  <div id="app">
    <p>Click the button to change its color.</p>

    <button
      role="link"
      @click="handleClick"
      class="btn non-active"
    >
      Click
    </button>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick(event) {

      // 👇 Alternate classes
      event.currentTarget.classList.toggle('non-active');
      event.currentTarget.classList.toggle('active');
    },
  },
};
</script>

<style>
.btn {
  border: 1px solid gray;
  padding: 8px 16px;
  font-family: Arial;
  font-size: 1.1em;
  box-shadow: 0 2px 5px #c0c0c0;
}

.active {
  background-color: white;
  color: black;
}

.non-active {
  background-color: rebeccapurple;
  color: white;
}
</style>
Clicking the element toggles its color.
Clicking the element toggles its color.

The classList.toggle() method removes a class from an element if it is present. Otherwise, it adds the class to the element.

How to Open a Link in a New Tab in Vue

To open a link in a new tab in Vue, create an anchor (<a>) element and set its target attribute to _blank, e.g., <a href="https://codingbeautydev.com" target="_blank"></a>. The _blank value specifies that the link should be opened in a new tab.

App.vue

<template>
  <div id="app">
    <a
      href="https://codingbeautydev.com"
      target="_blank"
      rel="noreferrer"
    >
      Coding Beauty
    </a>

    <br /><br />

    <a
      href="https://codingbeautydev.com/blog"
      target="_blank"
      rel="noreferrer"
    >
      Coding Beauty Blog
    </a>
  </div>
</template>

The target property of the anchor element specifies where to open the linked document. By default target has a value of _self, which makes the linked page open in the same frame or tab where it was clicked. To make the page open in a new tab, we set target to _blank.

We also set the rel prop to noreferrer for security purposes. It prevents the opened page from gaining any information about the page that it was opened from.

The link is opened in a new tab.
The link is opened in a new tab.

Sometimes we’ll prefer a button instead of a link to open the new tab when clicked.

To open a link in a new tab on button click, create a button element and set an click event listener that calls the window.open() method.

App.vue

<template>
  <div id="app">
    <p>
      Click this button to visit Coding Beauty in a new tab
    </p>

    <button
      role="link"
      @click="openInNewTab('https://codingbeautydev.com')"
    >
      Click
    </button>
  </div>
</template>

<script>
export default {
  methods: {
    openInNewTab(url) {
      window.open(url, '_blank', 'noreferrer');
    },
  },
};
</script>
The link is opened when the button is clicked.
The link is opened when the button is clicked.

We use the open() method of the window object to programmatically open a link in a new tab. This method has three optional parameters:

  1. url: The URL of the page to open in a new tab.
  2. target: like the target attribute of the <a> element, this parameter’s value specifies where to open the linked document, i.e., the browsing context. It accepts all the values the target attribute of the <a> element accepts.
  3. windowFeatures: A comma-separated list of feature options for the window. noreferrer is one of these options.

Passing _blank to the target parameter makes the link get opened in a new tab.

When the button is clicked, the event listener is called, which in turn calls window.open(), which opens the specified link in a new tab.