How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently returns undefined. Strangely enough, the DevTools in Vue indicate that this getter does indeed have a value. How can I correctly retrieve the value of the getter within the function?

QUERY:

While the filters are effectively displayed on the interface when used in the template, they inexplicably return an undefined result within the toDo function. This peculiar behavior is what I aim to comprehend.

<div
    v-for="filter in filters"
    :key="filter.id">
    <v-checkbox
        v-for="(item, index) in filter.values"
        :label="filter.description_values[index]"
        :value="item"
        :key="item"
        v-model="filter.selected_values"
        hide-details>
    </v-checkbox>
    <v-select
        v-if="filter.widget==='single_dropdown'"
        v-model="filter.selected_values"
        :items="filter.filter_values"
        label="Select ..."
        dense
        solo
        @change="toDo">
    </v-select>
</div>

***
computed: {
  ...mapGetters('store', [
    'filters'
  ]),
},
methods: {
  toDo: async (value) {
    await console.log(this.filters) // result: undefined
  }
}
***

Vuex Storage:

import { api } from '../../services/api'

export default {
  namespaced: true,
  state: {
    filters: null
  },
  getters: {
    filters: state => state.filters
  },
  mutations: {
    setStateValue: (state, {key, value}) => {
       state[key] = value
    }
  },
  actions: {
    getFilters: async (context) => {
      await api.get('/api/filters').then((response) => {
        context.commit('setStateValue', {
          key: 'filters',
          value: response.data
        })
      })
    }
  }
}

Answer №1

When using mapGetters in your computed properties, consider calling all getters within a single array:

computed: {
  ...mapGetters(['store', 'filters']),
},

Answer №2

In the store, the filters getter is located in the root and not within a module, allowing you to access it without any namespacing required:

computed: {
  ...mapGetters(['filters']),
},

Answer №3

If the Vuex code you provided is for your main store (not a module), you should remove namespaced: true as it's only used for vuex modules.

If the Vuex code you provided is not part of a Vuex module, you can simply map getters like this:

computed: {
  ...mapGetters(['filters']),
},

For more information, check out https://vuex.vuejs.org/guide/modules.html#binding-helpers-with-namespace

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

Automated Facebook Wall Publishing

I have successfully integrated a feature in my application where users can post status updates, photos, and URLs on their Facebook Like stream. I have also added an option for users to post directly on Facebook by including a checkbox. When the user clicks ...

Assign local variable in Mongoose using query results

I created a function to query MongoDB for a credential (simplified): var query = Credential.findOne({token: token}); return query.exec(function (err, credential) { if (err) return null; return credential; }); The next step is to use this credent ...

Issue: tanstack_react_query's useQuery function is not recognized

Error: (0 , tanstack_react_query__WEBPACK_IMPORTED_MODULE_3_.useQuery) is not a function While implementing data fetching in my Next.js project using @tanstack/react-query, I encountered the above error message. Below is the code snippet where the issue ...

Have the getter functions for reactive objects in Vue 3 been transformed into computed values?

Is the memoization of bookCount in this instance handled equivalently to a computed reference? const author = reactive({ name: 'John Doe', books: [ 'Vue 2 - Advanced Guide', 'Vue 3 - Basic Guide', 'Vue 4 - ...

Update the text within a table in real time by simply checking a box

I've got some data in JSON format that I've converted into an HTML table. Now, my goal is to update the text from False to True if a checkbox is checked. How can I achieve this? Below is the code used to create the HTML table: $.each(result, fu ...

Modifying ID styling using JavaScript on Internet Explorer

I need to change the CSS display property from none to block using JavaScript, but only for Internet Explorer. My current code is not working for the ID #backfill-image. <script> function checkForIE() { var userAgent = navigator.userAgent; ...

Using JavaScript to search JSON objects based on key value pairs

Consider a scenario where you have an array of objects in users.json: {"key":"userSubscriptions","value": [{"channel":"Netflix","user":"Bobby","region":"NA"}, [{" ...

The ajax success response transforms when using @html.raw

In my Razor viewpage, I have the following jQuery code: $(document).ready(function () { var listValues = @Html.Raw(Json.Encode(Session["list"])); $("#nsline").click(function () { alert(listValues) $.ajax({ type: "P ...

Having issues sending multiple variables to PHP through Ajax

Trying to pass three variables through the URL using Ajax - one constant and two from a date picker. The constant passes fine, but the date variables are only passing as their names. Here's the code for the date pickers: <tr> ...

Can't decide between ngOnInit() and ngAfterContentInit()?

As a newcomer to Angular, I sometimes get confused about the ngOnInit() and ngAfterContentInit() lifecycle hooks. According to the official documentation: ngOnInit() : This hook is used to initialize the directive/component after Angular has displayed the ...

Dynamic Filtering with jQuery List

I'm attempting to create a dynamic filter list on keypress event. For example, if I type "It" into the input field, the elements that do not match this value will be hidden. I'm unsure if the code structure I have implemented below effectively ac ...

Redirect the URL in react-snap to a new URL with a forward slash at the end

I recently implemented react-snap to generate static HTML for my website. However, I encountered some SEO issues after implementing react-snap. The old URLs (which were without slashes) are now redirecting to new URLs with slashes. For example: This URL: ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

Is there a way to extract a token from the URL in a Nextjs/React application?

I am currently developing a project that relies heavily on API integration. My front-end interface is built using React and Next.js, while the back-end API is developed with Laravel. Within my front-end page, I have implemented a token in the URL to help ...

What is the best way to create a self-referencing <div> in HTML?

After extensive research, I turn to seeking advice and guidance on Stack Exchange. I have a seemingly straightforward goal in mind. I want to create a <div> id/class that will automatically generate a link to itself using scripting of some sort. Be ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

"Clicking on the jQuery carousel dots results in always navigating back to the first item

Creating a carousel using basic jquery, utilizing the .css() rule to toggle opacity between slides. The goal is to have each dot trigger the display of its corresponding slide while hiding the others. Currently trying: $('.dot').click(function( ...

The form is functioning properly on mobile devices but is currently experiencing issues on the server

Everything runs smoothly when accessing the website and using the form on localhost. However, once it's uploaded to a server, the form only functions correctly on desktop devices. On mobile, the form fails to filter and displays all professionals inst ...

Looking for ways to streamline your React and Vue projects by reducing the number of

Coming from a background in emacs and xterm, I am accustomed to working with just a few files and having complete control over my work. Now I am delving into the world of React and Vue, but I was taken aback when I saw the sheer number of files generated f ...