Courses
Vue Foundations Vue Fullstack Vue Enterprise
Articles
Latest Topics
More
Newsletter Sponsorship Discord About

5 Awesome VueUse Browser Related Composables

Anthony Gore

Anthony Gore | June 5th, 2023 | 4 min read
vue.js VueUse Composables

VueUse is a collection of essential Vue Composition Utilities for interacting with various browser, sensor, animation, and state apis, plus more to easily add functionality to your Vue applications. These functions are designed to be simple to use and can be applied to a wide variety of projects.

There are of lots of composables to choose from but in this article, we will take a look at 5 of some awesome VueUse functions for working with the browser. We will discuss how each function works and how you can use it in your Vue.js applications.

By the end of this article, you will have a quick understanding of VueUse and how you can leverage these functions to create some awesome Vue.js projects or components.

So without further ado, let's get started!

But wait 🛑 hold on. Before getting to the good stuff we need to make sure to setup our project first.

Installation

Before trying out these functions let’s setup our project

npm init vue@latest

✔ Project name: VueUse-test
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add an End-to-End Testing Solution? … No / Cypress / Playwright
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes

cd VueUse-test
npm install
npm run dev

Now our Vue.js project is running. We will need to install VueUse in our project. Let’s proceed

npm i @vueuse/core

Now our Vue.js project is setup with VueUse also install. We are good for blast off 🚀

useBreakpoints

VueUse composable for providing Reactive viewport breakpoints. This may be useful in cases where we want to trigger some events on specific screen sizes.

import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'

// use Tailwind device breakpoints
const breakpoints = useBreakpoints(breakpointsTailwind)

const smAndLarger = breakpoints.greaterOrEqual('sm') // sm and larger
const largerThanSm = breakpoints.greater('sm') // only larger than sm
const lgAndSmaller = breakpoints.smallerOrEqual('lg') // lg and smaller
const smallerThanLg = breakpoints.smaller('lg') // only smaller than lg

// or you can set you breakpoints

import { useBreakpoints } from '@vueuse/core'

const breakpoints = useBreakpoints({
  tablet: 640,
  laptop: 1024,
  desktop: 1280,
})

const laptop = breakpoints.between('laptop', 'desktop')

Not take a look at a quick demo.

<script setup>
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'

// use Tailwind device breakpoints
const breakpoints = useBreakpoints(breakpointsTailwind)

const mobileView = breakpoints.smallerOrEqual('sm')
const TabletView = breakpoints.smaller('lg')
const desktopView = breakpoints.greaterOrEqual('lg')
</script>

<template>
  <div v-if="mobileView">Mobile View</div>
  <div v-if="TabletView && !mobileView">Tablet View</div>
  <div v-if="desktopView">Desktop View</div>
</template>

useClipboard

The Reactive Clipboard API allows for the handling of clipboard commands (cut, copy, and paste) and enables asynchronous reading from and writing to the system clipboard. Access to the clipboard's content is regulated by the Permissions API, ensuring that reading or modifying the clipboard is only possible with the user's permission.

import { useClipboard } from '@vueuse/core'

const source = ref('Hello')
const { text, copy, copied, isSupported } = useClipboard({ source })

<div v-if="isSupported">
    <button @click='copy(source)'>
      <!-- by default, `copied` will be reset in 1.5s -->
      <span v-if='!copied'>Copy</span>
      <span v-else>Copied!</span>
    </button>
    <p>
      Current copied: <code>{{ text || 'none' }}</code>
    </p>
  </div>
  <p v-else>
    Your browser does not support Clipboard API
  </p>

Now blast off to a quick demo.

useScriptTag

useScriptTag is a Script tag injecting composble. It allows for us to inject scripts into our head element only when a specific component is mounted. Very helpful to control what scripts are loaded on a particular page.

import { useScriptTag } from '@vueuse/core'

useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  // on script tag loaded.
  (el: HTMLScriptElement) => {
    // do something
  },
)

Script will be automatically loaded when component is mounted and removed when the component is unmounted or you can choose to have manual control over when when to load and remove script by setting manual: true.

import { useScriptTag } from '@vueuse/core'

const { scriptTag, load, unload } = useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  () => {
    // do something
  },
  { manual: true },
)

// manual controls
await load()
await unload()

let’s try a quick demo with lottie animations

<script setup>
//import { ref, computed } from "vue";
import { useScriptTag } from "@vueuse/core";

useScriptTag(
  "https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js",
  // on script tag loaded.
  () => {
    console.log("hello")
    
  }
);
</script>

<template>
  <div>
    <lottie-player
      src="https://assets8.lottiefiles.com/packages/lf20_M9p23l.json"
      background="transparent"
      speed="1"
      style="width: 300px; height: 300px"
      loop
      controls
      autoplay
    ></lottie-player>
  </div>
</template>

useTitle

UseTitle provides a Reactive document title composable. It makes our document title reactive so we can change our Documents title right from our component.

import { useTitle } from '@vueuse/core'

const title = useTitle()
console.log(title.value) // print current title
title.value = 'Hello'

You can pass a ref to the title to automatically change the title when source ref changes

import { useTitle } from '@vueuse/core'

const messages = ref(null)

const title = computed(() => {
  return !messages.value ? 'No message' : `${messages.value} new messages`
})

useTitle(title) // document title will match with the ref "title"

//template
<template>
<div>
<input type="text" v-model="title" />
</div>
</template>

useMediaControls

useMediaControls provides reactive media controls for both audio and video elements. We are provided with lots of options to control or grab information from our video or Audio file. Very handy if you are looking to create a Vue.js powered media player.

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useMediaControls } from '@vueuse/core'

const video = ref()
const { playing, currentTime, duration, volume } = useMediaControls(video, { 
  src: 'video.mp4',
})

// Change initial media properties
onMounted(() => {
  volume.value = 0.5
  currentTime.value = 60
})
</script>

<template>
  <video ref="video" />
  <button @click="playing = !playing"> Play / Pause</button>
  <span>{{ currentTime }} / {{ duration }}</span>
</template>

Conclusion

In conclusion, we've explored five awesome VueUse Browser composables that have the potential to help you create awesome Vue.js application. From handling clipboard operations to media controls, these composables offer powerful functionality right at your fingertips.These are just a few of the many awesome VueUse functions that are available. By using these functions, you can effortlessly add awesome functionality of your Vue.js applications.

But there's more! Take your VueUse skills to the next level with Vue School's "Vue Use for Everyone" online course. Gain hands-on experience, practical techniques, and join a vibrant community of learners as you unlock the potential of VueUse and create extraordinary Vue.js applications.


Anthony Gore

About Anthony Gore

I'm Anthony Gore and I'm a web developer with a crush on Vue.js. I'm a Vue Community Partner, curator of the weekly Vue.js Developers Newsletter, and the creator of Vue.js Developers.

If you enjoyed this article, show your support by buying me a coffee. You might also enjoy taking one of my online courses!

Related posts

Click to load comments...

Courses
  • Vue Foundations
  • Vue Fullstack
  • Vue Enterprise
Articles
  • Latest
  • Topics
Newsletter
  • Join
  • Sponsorship
More
  • Discord
  • Vue.js jobs
  • About

Vue.js Developers © 2021. View our privacy policy .

  • RSS
  • |
  • Atom