Creating a Utils class in Vue.js with seamless access to Vuex through this.$store

I have a situation where I need to retrieve state from the Vuex store using this.$store. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution.

Here is my plugin implementation:

index.ts

import _ from 'lodash'

export default {
  install: function (Vue) {
    Vue.prototype.$fetchVillager = function () {
      const players = this.$store.state.players
      const village = this.$store.state.villages.find(value => value.id === 0)
      const villagerIds = village.villagers

      const villagers = _.filter(players, function (player) {
        return villagerIds.includes(player.id)
      })
      if (!_.isNil(villagers)) {
        return villagers
      }
      return []
    }
  }
}

As you can see, I am utilizing this.$store.state.players to access the Vuex state. Implementing this functionality is straightforward and it works as intended, as shown here:

computed: {
    villagers: function () {
      return this.$fetchVillager()
    }
  }

However, by using Vue.use(MyPlugin), this function becomes accessible globally. I would prefer to restrict its usage to specific components where I need it (currently three components).

Ideally, I would like to import VillageServices from '@/services/villageServices.ts' and leverage the exposed functions from there. Unfortunately, this approach does not allow me to access Vuex's this.$store since I am not tied to a Vue instance with the imported class.

Is there a way to achieve the desired behavior?

Answer №1

One possible solution is to implement a mixin.

const residents = {
    methods: {
        $fetchResidents() {
            // utilize this.$store here
        }
    }
};

const myView = new Vue({
    mixins: [residents],
    computed: {
        inhabitants() {
            return this.$fetchResidents();
        }
    }
});

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

Yarn Plug'n'Play was unable to locate the module during the next build

Currently, I am in the process of developing a Next.js project with yarn's Plug'n'Play feature. In this project, I have created several pages and added various packages, including mathjs: '^10.3.0' to assist me in parsing user inpu ...

Creating a dynamic template in a single file component with Vue.js 2

I've been looking for a way to have a single file component load its template via AJAX. After doing some research, I stumbled upon the concept of dynamic components. To achieve this, I created a parent component that imports a child component and rend ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

Minification of CSS - Vuetify

While working on my Nuxt project with Vuetify, I noticed that the page source is quite lengthy with 26k lines of code, most of which is generated by Vuetify's CSS. On comparing it with other pages, I see shorter code with difficult-to-read CSS. Is the ...

Tips for integrating Reactjs with Chessboard.js

Recently, I stumbled upon chessboardjs (https://chessboardjs.com/) as a way to hone my React coding skills. However, I hit a roadblock while trying to implement a simple example of displaying the chess board in my application. The documentation instructed ...

Turning XSD into TypeScript code

Stumbling upon this tool called CXSD, I was intrigued. The documentation describes cxsd as a streaming XSD parser and XML parser generator designed for Node.js and TypeScript (optional but highly recommended). It seemed like the perfect solution for my ne ...

When transitioning to generics, the narrowing of types in TypeScript is sometimes lost

I am intrigued by this scenario where Test1 fails while Test2 succeeds. I wonder if there is a way to have Test1 pass without altering the generic signature: enum TableType { Shipment = "Shipment", Batch = "Batch", } type Test& ...

Incorporate an image icon into an Angular grid

Currently, I am in the process of building a web application using Angular. The main goal is to create a grid and color specific cells based on data input. Below is the snippet of my HTML code: <mat-grid-list cols="10"> <mat-grid-tile * ...

At what juncture is the TypeScript compiler commonly used to generate JavaScript code?

Is typescript primarily used as a pre-code deployment tool or run-time tool in its typical applications? If it's a run-time tool, is the compiling done on the client side (which seems unlikely because of the need to send down the compiler) or on the s ...

Vue.js error: Trying to access an undefined property

Here is my Vue instance setup: const vueApp = new Vue({ el: '#vue-wrapper', data: { items: [] }}); Utilizing a v-for loop in index.html.eex: <div v-for="item in items[0].subItems">{{ item.name }}</div> In this scri ...

stopping Vue from aggressively recycling DOM elements

Consider the snippet below: <template v-if="tryIsMobile" > <div class='device device-mobile-portrait' :class="deviceClass"> <div class="device-scroller-container"> <div class='device-scroller'> ...

How can I update a property within an object in a sequential manner, similar to taking turns in a game, using React.js?

I am currently working on a ReactJs project where I am creating a game, but I have encountered an issue. I need to alternate turns between players and generate a random number between 1 and 10 for each player, storing this random number inside their respec ...

Infer the types and flatten arrays within arrays

I am currently working on creating a custom function in typescript that can flatten nested arrays efficiently. My current implementation is as follows: function flattenArrayByKey<T, TProp extends keyof T>(array: T[], prop: TProp): T[TProp] { re ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Encountering an issue in the test file when using react-router-dom v6: "The 'history' property is not found on the 'IntrinsicAttributes & RouterProps' type."

Main script: import { useContext, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import AuthenticationContext from './AuthenticationContext'; function HandleOAuthCallbackRoute() { co ...

What are the steps to use the vue-text-highlight feature?

I am attempting to implement an example from the basic usage section of https://github.com/AlbertLucianto/vue-text-highlight. However, upon opening index.html in Firefox, I am only greeted with a blank page. You can find the code I am using at https://git ...

Is there a way to utilize the 'interval' Rxjs function without triggering the Change Detection routine?

My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every se ...

What can I do to condense the length of b-dropdown-item-button or make the text wrap instead?

DropDown Currently, I am utilizing Bootstrap-vue. My goal is to ensure that the b-dropdown-item-button wraps the text it displays. Is there a recommended approach for achieving this? <template> <b-dropdown menu-class="py-1" text="··· Action ...