Ensure prototype is easily accessible within vuex

Within my app.js file, I implemented a functionality to enable translation in Vue:

Vue.prototype.trans = string => _.get(window.i18n, string);

This feature works perfectly when used in my Vue files:

{{ trans('translation.name') }}

However, I encountered an issue while working with vuex and needing to translate some content within a module:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default {
    namespaced: true,

    state: {
        page: 1,
        criterias: [
            {
                name: this.trans('translation.name'),
                filter: "life",
                active: false
            }
     }
 }

In this context, this.trans('translation.name') does not function as intended. How can I resolve this issue and make it work as expected?

Answer №1

I believe modifying the Vuex prototype can be considered a less-than-ideal practice, especially when it's not absolutely necessary in this specific scenario.

My recommendation is to create a separate file named localization.js, where you can set up the i18n plugin and export a named function that returns the same i18n instance.

// localization.js

const i18n = new VueI18n({ ... });

export const getLocalization = () => i18n;

export default i18n;

Then, within your Vuex module, import the getLocalization function and invoke it to access the i18n instance for translations.

// vuex-module.js

import Vue from 'vue';
import Vuex from 'vuex';
import { getLocalization } from './localization';

Vue.use(Vuex);

const i18n = getLocalization();

export default {
  state: {
    criteria: i18n('translation.name'),
  },
}

Answer №2

If you're looking for a solution, here's an idea: why not try moving the initialization of criterias from store.js to App.vue by using a mutation?

Check out the code below:

state: {
    page: 1,
    criterias: []
},

mutations: {

    setCriterias(state, payload) {
        state.criterias = payload;
    },

}

In your App.vue, add this beforeMount method:

beforeMount() {

   this.$store.commit( 'setCriterias' , [

        {
            name: this.trans('translation.name'),
            filter: "life",
            active: false
        }

   ])

}

Answer №3

Since your translation content is accessible globally through `window.i18n`, have you considered creating another method similar to the `trans` method you add to `Vue.prototype` in your store module?

If you're worried about having to make changes to this method in two separate locations down the line, you could define a translation module with this single method and import it both where you set Vue.prototype and within your store module.

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

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

Troubleshooting Event Tracking Problems with Brave Browser on PostHog

After successfully implementing Posthog with React and testing it on Chrome and Firefox, we encountered issues when trying to test it on Brave/Microsoft Edge Browsers. It appears that the default ad blocker feature in these browsers is causing the problem. ...

Is there a way to verify user credentials on the server using FeathersJS?

Currently, my single-page app is utilizing feathers client auth and a local strategy for authentication. I have implemented various middleware routes and I am looking to verify if the user is authenticated. If not, I would like to redirect them to /. Bel ...

"Improvements required for the search and filter functionality in the JSON

My JSON function retrieves image data and displays it in panels. Here is an example of the code: $.getJSON('iproducts.json',function(products){ var output = ""; $.each(products.appleitems, function(i, product) { output += "<di ...

You are unable to select the element in IE if there is an image in the background

Apologies for coming back with the same question, as I realize now that I was not clear in my explanation yesterday. You can find the codepen here (please note that it may not open in IE8). My issue is with dragging the 'move-obj' element in IE b ...

Displaying a date picker within a fragment nested inside another fragment

Encountering a slight issue with implementing a Date picker using a fragment into another fragment. Upon clicking the button to load the Date picker, an error message is logged: java.lang.ClassCastException: com.example.buzzamaid.HomeActivity cannot be ca ...

Tips for updating and triggering useEffect when the router changes in React JS

I have a ChartPage function that is being called three times within three different routers. Inside the ChartPage function, I am using "useEffect" to update some variables based on the selected route. However, for some reason, it only triggers once, and wh ...

Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay). My issue arises from ...

What is the best way to refresh a navigation bar after making an API request, such as when using Google Sign-In?

Struggling to grasp the hook concept in this particular scenario: The flow goes like this - the user logs in with Google, which updates the session state. Consequently, the visitorType state transitions from 'viewer' to 'buyside'... A ...

`Creating the perfect bar``

Currently working on my resume using Angular and I am interested in incorporating a visual representation of my skill level in specific subjects. Came across something that caught my eye here: The challenge now is figuring out what exactly to search for i ...

Having trouble making `overflow: hidden` work correctly when using padding on an element with `height:

Looking for some coding help here. My aim is to create a customized select menu with a sleek animation effect. I initially decided to set the default height to 0 and use overflow: hidden, then switch it to auto when .active class is applied. But, I'm ...

Tips for modifying the function of an Electron application using an external JavaScript file

This is the project structure I envision. https://i.stack.imgur.com/ocRp9.jpg kareljs folder houses an Electron app, and upon running npm start within that directory, a window appears and executes the run method of karel.js when the button Run Karel is ...

Trigger a function from a Bootstrap modal

Here is a preview of my HTML code : <form action="form2_action.php" method="post"> <table> <tr> <td>First Name </td> <td>:</td> <td><input type="text" id="f ...

How to make an AJAX request in jQuery / JavaScript after a specific time interval has passed

Here is the code snippet I'm working with: $('input.myinput').each(function(){ var id = $(this).val(); var myajax = function(){ $.ajax({ url: ajax_url, type: "GET", data: ({ code: id ...

Combine and emphasize several gridview rows into a single highlighted unit

Imagine you have a gridview that looks like this: FAMILY GROUP COLOR =============================================== | | Poodle | Blue ROW1 | DOG | German Shepherd | Red | | Pitbul ...

The conditional statement to check for an empty object does not trigger any actions

My goal is to display a success message once users successfully register without any errors. I have an errors reducer object in Redux that stores errors sent from the backend. The logic is set up so that if the errors object is empty, it shows the success ...

Managing the scrolling direction horizontally with waypoints.js

As I work on creating a custom wizard form with waypoints, I've encountered an interesting issue that has left me puzzled. In my sample CODEPEN, you can see two pages of the wizard process to better understand the problem. Upon clicking the forward ...

Ways to resolve issues with v-model rendering errors

I currently have code fragments within my index.blade.php file that look like this: The content section: . . . <div class="col-12 col-md-12 mb-3"> <label for="attachment" text-muted">Attachment</label> &l ...

What is the reason for the checkboxes in vuejs not being rendered with the checked attribute set

When working on an edit form, I encountered a situation where I had multiple options to choose from. These options were fetched via ajax using axios and assigned to the variable permisos in the component. Later, these options are rendered through a v-for l ...

problem with accessing a website input area

Upon clicking outside the "subheader", I need to display the words "register" and "login" again, unless something is typed into the input fields... that's all there is to it, just click outside the subheader $(document).ready(function() { $(&ap ...