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

Presenting JSON data in a table format on-the-fly even without prior knowledge of the data's structure or field names

When working with my application, I will be receiving data in JSON format and I am looking to showcase this data in a tabular form within a web browser. It's important to mention that I won't know beforehand the structure or field names of the re ...

Tips for incorporating an onClick event into a variable beyond the class extension

Currently utilizing React/Redux in this scenario. At the beginning of my code, outside of the class extends block, I have: const Question10 = () => (<div> <p>Insert question here</p> <input place ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...

Sinon Stub generates varying values with each invocation

I'm pretty new to TypeScript and JavaScript, but I've managed to create a functioning VScode extension that I'm really happy with. However, I'm running into some issues with my Mocha tests. Here's a snippet of the code I'm str ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

Problem with bcrypt npm installation on Mac OS X 10.9 and Node v0.10.22

Operating System Information: Mac OS X 10.9 Node version: v0.10.22 An error occurs when attempting to install the bcrypt package. Any suggestions on how to resolve this issue? Any assistance would be highly appreciated. > [email protected] install /U ...

"Combining Angular and jQuery for powerful web development

I am looking to develop an application using Angular and incorporate numerous jQuery animations and jQuery UI effects (such as animate, fadeIn, fadeOut, etc). Is it feasible to use jQuery functions in conjunction with Angular? ...

Verification of Radiobox Groups in AngularJS

Could you please help me with validating a radiogroup using AngularJS, which is instantiated within an additional directive? The validation requirement is that the User must not be able to submit unless one of the radio buttons has been selected. This is ...

Prevent a specific folder from being included in expressjs routing

When using my expressjs app, I load public assets like this: app.use(express.static(__dirname + '/public')); Afterwards, I redirect all requests to the index, where every path is handled by Backbone app.get('*', routes.index); I am ...

Retrieve anchor elements from multiple HTML documents

I have a challenge that I'm not certain is achievable, but I am attempting to extract all anchor tag links from several HTML files on my website. Currently, I have developed a PHP script that scans various directories and subdirectories to create an a ...

Successfully resolving the API without encountering any response errors, even after sending a response

Once the data is successfully saved in the database and the image upload is completed, I am attempting to send res.json. However, I keep encountering the error message API resolved without sending a response for /api/auth/registeration, this may result in ...

Tips for retrieving javascript-generated HTML content

Currently, I'm attempting to retrieve article headlines from the NY Times website. Upon inspection, it appears that the HTML is being generated by Javascript since it's only visible when using the 'inspect element' feature in Firefox. ...

Timeout for jQuery animations

My jQuery animation script is causing an issue where it does not finish the animation before returning to the parent function. Specifically, the JavaScript code changes a background color, calls the animate function, the animation starts but doesn't c ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

Mastering the map() function in Vue.js 2

As I start learning vue.js, I am facing some challenges. I need to implement a dictionary analog in JavaScript, known as a map. However, I'm unsure of where to define it. The map should be utilized in both the checkDevices() method and within the HTML ...

Trigger an event when hovering over a disabled item in React using material-ui's tooltip feature

I've been trying to figure out how to hover over a disabled item with a tooltip, but it seems that disabled items don't trigger any events. I attempted wrapping my elements in another div as a workaround, but unfortunately, it didn't work. I ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Can you extract information from the XML file and modify the anchor tags?

<description> <div class="field field-name-field-image field-type-image field-label- hidden"><div class="field- items"><div class="field-item even"><a href="/news/news/vg"> ...