Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 10, 2020 01:50 pm GMT

Web Monetization in Vue

There is an awesome post for getting started with web monetization in React and was inspired to make one using Vue 3.

We're going to use a no-bundle dev server for Vue 3 called vite which allows us to develop Vue apps with Single-File Components without any bundling during development.

Create a vite app

Open up your terminal and do the following:

$ npx create-vite-app <project-name>$ cd <project-name>$ npm install$ npm run dev

Creating a hook to see if a user is web monetized

In the root of your project folder, create a file named use-web-monetization.js and paste the code below.

import { ref, onMounted } from "vue";export const useWebMonetization = () => {  const isMonetized = ref(false);  const isLoading = ref(true);  onMounted(() => {    if (!document.monetization) {      // No web monetization polyfill is installed (e.g. Coil).      isLoading.value = false;      isMonetized.value = false;      return;    }    // Check the value of document.monetization.state    // to see if a user is web monetized.    const { state } = document.monetization;    if (state === "stopped") {      // Not currently sending micropayments, nor trying to.      isLoading.value = false;      isMonetized.value = false;    }    // Determine when Web Monetization has started actively paying    document.monetization.addEventListener("monetizationstart", (event) => {      isLoading.value = false;      isMonetized.value = true;    });  });  return {    isMonetized,    isLoading,  };}

We created a file that has a reusable hook named useWebMonetization that returns isMonetized and isLoading states.

And now we can use it inside any .vue file like below.

<template>    <div>      <div v-if="isLoading">        Loading...      </div>      <div v-else-if="isMonetized">        Some exclusive content!      </div>      <div v-else>        Show ads here!      </div>    </div></template><script>import { useWebMonetization } from "./use-web-monetization";export default {  setup() {    const { isLoading, isMonetized } = useWebMonetization();    return {      isLoading,      isMonetized,    };  }};</script>

Testing Web Monetization

test-web-monetization is a website that provides a bookmarklet that we can use to test our projects without signing up for a Coil account.

Good luck to everyone!


Original Link: https://dev.to/sorxrob/web-monetization-in-vite-455

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To