Implementing Vue plugins in your Store: A step-by-step guide

Looking for the proper way to integrate a plugin within a Vuex module or plain JS module. Currently using an event bus but unsure if it's the best approach. Any guidance would be appreciated.

Plugin1.plugin.js:

const Plugin1 = {
  install(Vue, options) {
    Vue.mixin({
      methods: {
        plugin1method(key, placeholderValues = []) {
          return key;
        },
      },
    });
  },
};

export default Plugin1;

In App.vue:

Vue.use(Plugin1, { messages: this.plugin1data });

In store / plain-js module:

const vue = new Vue();
const plugin1method = vue.plugin1method;

Answer №1

If you want to access your Vue instance, simply use this._vm;
To access the Vue global, you can do so by using import Vue from 'vue'; and then calling Vue;

It seems like you have defined an instance method, in that case, you would use the former syntax (this._vm.plugin1method())


update

I cannot recommend a specific way of using it without seeing how your function is defined within your plugin.

However, let me provide an example to demonstrate the distinction between instance and global:

const myPlugin = {
  install: function(Vue, options) {
    // 1. add global method or property
    Vue.myGlobalMethod = function() {
      // some logic ...
      console.log("run myGlobalMethod");
    };
    Vue.mixin({
      methods: {
        plugin1method(key, placeholderValues = []) {
          console.log("run mixin method");
          return key;
        }
      }
    });
    // 4. add an instance method
    Vue.prototype.$myMethod = function(methodOptions) {
      console.log("run MyMethod");
      // some logic ...
    };
  }
};

Vue.use(Vuex);
Vue.use(myPlugin);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      this._vm.$myMethod();
      Vue.myGlobalMethod();
      this._vm.$options.methods.plugin1method();  // <-- plugin mixin custom method
      state.count++;
    }
  }
});

When you trigger the increment with this.$store.commit('increment'), both methods will be executed

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

What is the best way to retrieve and display the heading of the current section that is being viewed using Bootstrap Vue's ScrollSpy feature?

I am currently using the Bootstrap Vue Scrollspy feature in my project with Nuxt js. The elements are correctly referenced and are successfully spying on the content. What I would like to achieve is having the ability to update a specific div with the curr ...

Automated deployment of Vue-CLI project on Firebase Hosting through GitHub actions

Having trouble with automatic deployments in my Vue-CLI project. I've been searching all day, received the key from firebase login:ci, but unsure where to place it in yaml files. Added FIREBASE_TOKEN as an environment variable on GitHub repo, follow ...

How to Use Framer Motion in Next.js for window.innerWidth Less Than 768

I am trying to use window.innerWidth to control the timing of an animation (Framer Motion) in my Next.js project, but I keep encountering the error message: ReferenceError: window is not defined Here's a simplified version of my ValuesSection.jsx co ...

What makes this effective in JavaScript?

While working on a project, I encountered the task of comparing coordinates in two arrays at the same index to see if they are identical. There are various methods to achieve this, but one particular approach piqued my interest. Why does it yield the expec ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

What methods can I use to accomplish the transformation of superimposed images?

Struggling with transforming a content box on my webpage. I have a div containing three overlapping images positioned using Grid, and I want to scale one of them to fill the entire div when scrolled over. While I managed to achieve this effect, I'm un ...

Tips for utilizing jQuery to substitute strings within a content variable?

$content = "Please locate the student results where Date of birth **IS BETWEEN** 2012-02-18 00:00:00 AND 2013-02-18 00:00:00 AND name **IS NOT EQUAL TO** 'John' AND marks **IS BETWEEN** 40 AND 75 AND grade **EQUAL TO** 'A' AND AGE **I ...

Tracking the email field in a React form with refs

Hey there! I'm a music engineer working on my own personal website using React. I'm currently facing an issue with creating a contact form that allows users to input a subject in a text field, a message in a textarea, and then click a "reach out" ...

Organize your Vue JS code by keeping all imports in separate files

Currently, I am delving into the realm of Vue.js and find myself faced with the task of loading numerous JSON files into my Vue project. Initially, I thought about directly importing each JSON file in the main file like so: //Index.vue <script> impo ...

NodeJS: Increasing memory consumption leads to system failure due to recursive scraping

Currently, I am utilizing a GET URL API in NodeJS to extract various data by looping through the months of the year across multiple cities. For each set of parameters such as startDate, endDate, and location, I invoke a scrapeChunk() function. This functio ...

Encountering difficulties in fetching data with formData in nextJS

Exploring the realm of NextJS and delving into server side actions. I'm facing a challenge with this specific request. import { revalidatePath } from "next/cache"; export async function submitIPCR(prevState: any, formData: FormData) { / ...

The issue with anchor links not functioning correctly in Chrome's desktop browser has been identified

I am interested in utilizing the greenfair CSS template available at this link. However, I have encountered an issue where the anchor links in the navbar do not work properly in Chrome (they function correctly in Firefox and IE). How can I resolve this pro ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

JavaScript causing Google custom search to not refresh results when updating search query

I am inputting user IDs into a textbox in my system. Upon submitting the ID, it fetches the name and address of the user and places it in the search box of a GCSE. document.getElementById("gsc-i-id1").setAttribute("value", this.searchqu ...

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

ReactJS Scripts are throwing an error indicating that the function require is not defined

Just starting out with React and I discovered that we can integrate React by adding the necessary scripts to our main index.html file. I followed all the steps to include the script and even made sure to add Babel since I'm writing my main App in JSX. ...

Executing jQuery after the body has finished loading

I'm trying to execute a JavaScript function once the body has finished loading. My framework loads the header and footer from static files, while the body content is dynamic. I read online that I should place the $(elem).load(function()) at the end of ...

Guide on inserting text within a Toggle Switch Component using React

Is there a way to insert text inside a Switch component in ReactJS? Specifically, I'm looking to add the text EN and PT within the Switch Component. I opted not to use any libraries for this. Instead, I crafted the component solely using CSS to achie ...

Determine the sum of all the values entered into the text fields

On my ASP.Net page, there is a screen where users can select between 1 and 5 text boxes to input an amount. Depending on certain criteria, a specific number of these edit boxes are displayed - no hiding involved. So if I choose to display 3 boxes, only 3 w ...

Leveraging callback functions for dynamically updating a JSON structure

Recently, I've been working on a db_functions.js file that includes several functions designed to interact with a database. Here's an excerpt from the script: function getUsers(client, fn){ //var directors = {}; client.keys('*' ...