Vue - Implementing plugin as a prototype functionality

For notifications in my application, I've incorporated the euvl/vue-notification library. Each time I need to notify the user, I have to include the following code:

If I'm within a Vue component:

this.$notify({
    group: 'panel',
    type: 'success',
    duration: 5000,
    text: 'message'
})

Or if I'm working in a .js file:

Vue.notify({
    group: 'panel',
    type: 'success',
    duration: 5000,
    text: `message`
})

I wanted to simplify this process by creating a support file, similar to an event bus, where I could just use the following line to trigger a notification:

this.$notify('message')

Despite my efforts, I haven't had success with this approach so far...

main.js

import Vue from 'vue'
import App from './App.vue'
import notifications from './support/notifications'

Vue.use(notifications)

new Vue({
  render: h => h(App)
}).$mount('#app')

notifications.js

import Vue from 'vue'
import Notifications from 'vue-notification'

Vue.use(Notifications)

export default function install(Vue) {
    Object.defineProperty(Vue.prototype, '$notify', {
        get(message) {
            return Vue.notify({
                group: 'panel',
                type: 'success',
                duration: 5000,
                text: message
            })
        }
    })
}

Answer â„–1

You are so close to achieving your goal, but consider using a different approach than Object.defineProperty. Instead of returning Vue.notify's return on the get method, try returning a reference to a function.

import Vue from 'vue'
import Notifications from 'vue-notification'

Vue.use(Notifications)

export default function install(Vue) {
    Object.defineProperty(Vue, 'notification', {
        get() {
            return notification;
        }
    })

    Object.defineProperty(Vue.prototype, '$notification', {
        get() {
            return notification;
        }
    })
}

function notification(message) {
    Vue.notify({
        group: 'panel',
        type: 'success',
        duration: 5000,
        text: message
    })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

How to utilize JS variables for filtering an array in EJS?

Is there a way to filter my user array based on the "username" variable in JavaScript? On the server side: var users = data.filter(u => u.id.startsWith('user_')).map(u => u.value); // [{"username": "arin2115", "som ...

Is it possible to use Vue files without relying on NodeJS?

Is it possible to host my app outside of Node.js while still using .vue files and possibly npm as a build system? I don't require backward compatibility, as long as it works on the latest Chrome development version. Are there any examples or tutorial ...

Guide to defining the encoding of an XML file with JavaScript

Hi there, I am currently facing an issue with encoding while creating a document using JavaScript. The problem is that the document rejects all non-ascii characters. For example, when passing the string "verificación", it gets replaced by "". Any suggesti ...

The correct way to integrate CSS-Modules into your Nuxt project

Currently, I am utilizing CSS Modules with Nuxt and have encountered some challenges while attempting to import a stylesheet into my JavaScript. Importing the stylesheet directly within the... <style module> @import './index.css'; </s ...

Inquiries regarding scopes, node.js, and express

I struggle with understanding scopes and similar concepts in various programming languages. Currently, I am working on an express application where I take user input, query an arbitrary API, and display the results in the console. To interact with the REST ...

Is it possible for Jquery to directly retrieve the form input without the need for a SET button in the script?

I have a script that functions as a basic countdown. All you need to do is enter a number, press the SET button, and click START for the countdown to begin. Although I primarily use this script in the gym, I often forget to hit the SET button after enteri ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...

Despite the headers being in place, the node is still the point of

I am facing an issue with two URLs residing on the same server, mydomain.com and api.mydomain.com In order to handle access-origin in my API, I have included the following code snippet: app.use(function (req, res, next) { // CORS headers res.head ...

Initiate an ajax request only when there are pre-existing ajax requests in the queue

Setting up the Form I've created a form that utilizes checkboxes to determine a selected number on a page: https://i.sstatic.net/BNQB0.png When a checkbox is selected, it triggers a call to a controller that saves the selection and returns the upda ...

When a user clicks anywhere on the website, the active and focused class will be automatically removed

I'm currently working with Bootstrap tabs on my website. I have three tabs, and when a user clicks on one, the active and focus classes are added to indicate which tab is selected. However, I've encountered an issue where clicking anywhere else ...

What is the process for showcasing specific Firestore items on a webpage?

database I've encountered an intriguing bug in my code that is proving difficult to resolve. The code involves a straightforward setup with React and Firestore, where items are listed on one page and their details are displayed on the next. However, t ...

In AngularJs, use ng repeat and ng switch to dynamically generate and display tables

I need help rendering a table with two columns using angularjs directives. <table> <tr ng-repeat="message in messages" > <td ng-switch-on="message.network" ng-switch when="twitter" ng-controller="TweetController"> <span> ...

Angular 15 experiences trouble with child components sending strings to parent components

I am facing a challenge with my child component (filters.component.ts) as I attempt to emit a string to the parent component. Previously, I successfully achieved this with another component, but Angular seems to be hesitant when implementing an *ngFor loop ...

Error encountered: JSHint is flagging issues with setting a background gradient using

I have been experimenting with animating a background gradient using jQuery, and here is the code snippet I am working with: this.$next.css('line-indent', 0).animate({ 'line-indent': 100 }, { "duration": 750, "step": functi ...

I'm curious about the purpose of the 'name' option within the routes array in Vue.js CLI3. Can you explain

Just starting out with vue.js and I'm focusing on practicing routing at the moment. Here's a snippet of my router.js: import Vue from 'vue' import Router from 'vue-router' import Home from './views/Home.vue' Vue.u ...

The button component in my React application is not functioning as expected, despite utilizing the useState and useEffect hooks

I'm having trouble with my Button not working, even though I am using useState and useEffect Check out the code below: import React, { useState, useEffect } from "react"; // import Timeout from "await-timeout"; import ...

Having trouble retrieving the NextAuth session data within Next.js 12 middleware

I've been working on implementing route protection using Next.js 12 middleware function, but I keep encountering an issue where every time I try to access the session, it returns null. This is preventing me from getting the expected results. Can anyon ...

AngularJS uses double curly braces, also known as Mustache notation, to display

I'm currently working on a project where I need to display an unordered list populated from a JSON endpoint. Although I am able to fetch the dictionary correctly from the endpoint, I seem to be facing issues with mustache notation as it's renderi ...