Ways to rerun a Vuex Getter

Perhaps there's a misunderstanding on my part regarding the concept of a getter in Vuex. Let's consider a scenario where I have a getter that fetches the size of a DOM element, such as a div. The code would look something like this:

const getters = {
  getContainerWidth (state) {
    return document.getElementById('main-content').clientWidth;
  }
}

Upon starting my application, all the getters are executed immediately. But what if the div is not available during startup? How can I re-run a getter?

Currently, I run the getter like this:

import store from '@/store'
store.getters['myModule/getContainerWidth']

I had a thought that maybe doing this would work:

store.getters['myModule/getContainerWidth']()

However, since store.getters is an object with properties and values that are not functions, it seems that I cannot re-run them.

Any suggestions or ideas?

Answer №1

It is important for getters to rely on the state field in order to be reactive. If you are trying to monitor changes in the clientWidth, it will not function properly.

If you wish to utilize it as a function, simply return a function from the getter:

const getters = {
  getContainerWidth (state) {
    return () => {
       let container = document.getElementById('main-content');
       return container ? container.clientWidth : 0
    };
 }

}

You can then use it by calling getContainerWidth()

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 method for creating a loop in Angular?

let m = 5; for (let i = 0; i < m; i++) { document.write(i); } What is the output of i in Angular? This code is not functioning as expected. $scope.B = []; angular.forEach([0, 1, 2, 3], function (value, index) { $scope.B.push ...

An error handling event for XHTML compliance, similar to the HTML onerror event, is designed to address the issue of

Below is a piece of code that handles hiding the placeholder (imagecontent) for dynamically populated empty images and their captions: <head> <script type="text/javascript"> function hideEmptyImage() { document.getElementById(&q ...

Changing the .load function based on user input

Can I replace a .load text with one that can be updated by a user using form input or similar method? My goal is to create a code that retrieves data using unique div IDs (specific to each employee) containing information within tables across various HTML ...

What is the best way to exclude a field from a Joi schema?

I've defined a Joi schema for a User with the following rules: const userRules = Joi.object({ name: Joi.string().pattern(new RegExp('^[A-Za-zÁÉÍÓÚáéíóúãõÃÕâêôÂÊÔ ]+$')).required(), email: Joi.string().email().requ ...

Adjusting the scope value directly within a directive

I have a validation message that starts off hidden when the page loads due to the ng-show attribute. When the user clicks to delete an entry, the confirmation message for successful deletion appears by changing the ng-show value to false. Now, I need to h ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

JavaScript: iterating over an array of objects containing nested arrays

Within my leaflet project, I created a function that accepts an array containing objects, each of which holds an array of markers and an ID to distinguish the group. Here is the sample array: var markerGroupArray = [ { features: [L.marker([39.61, -105.02 ...

Loading HTML content in a WPF WebBrowser without encountering security messages

Currently, I am developing a WPF application in which I create the content of an HTML file as a string (including some JavaScript functions for calculations). After generating the string, I save it as an HTML file on my local disk and then reload it using ...

The perfect method for creating template literals using a function

I have a function that accepts an argument called id and returns a template literal: const generateTemplate = (id) => { return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; dis ...

Modifying the CSS design of specific columns within a table created using JavaScript

A unique way to showcase JSON data in a table is by utilizing a for loop within a function. This method, however, does not assign an ID or Class to the table. To hide the final three columns of this table using CSS, the following code can be employed (whe ...

The component in vue.js does not recognize "action" as a valid method

I've encountered an issue while attempting to use an action as a method in a component. The error message displayed is: this.delete_notifaction is not a function notifaction.js export const actions = { add_notifaction({ commit }, notifaction) { ...

Issues have been encountered with the functionality of $rootScope

I am currently struggling with a code snippet in my loginCtrl.js file where I can't seem to get $rootScope to store the value of vm.userEmail. app.controller('LoginCtrl', function($timeout, $q, $log, $rootScope /*$auth*/, $location, $mdTo ...

Is it possible to manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...

A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be ...

Is it possible to animate share buttons using Framer Motion but staggering siblings?

I have a Share Icon that looks like: I'm looking to display the first 5 icons, with the 5th icon being the share icon. The remaining icons should appear below the share icon and expand to the right when someone taps or hovers over it (either tap or h ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

Tips for updating the First object based on certain matching values from the Second object using JavaScript

I am faced with the task of updating the listOfStudents Object by matching it with the homeworkResults Object based on their corresponding email values. Through comparison, when the email matches between the two Objects, I aim to retrieve the topic and suc ...

Adding information to an Excel spreadsheet using JavaScript

I'm facing a challenge in appending data to an existing Excel file using node.js. I've tried using the xlsx-writestream package with the code snippet below: var XLSXWriter = require('xlsx-writestream'); var writer = new XLSXWriter(&a ...

How can I dynamically resize a Bubble using CSV data based on the radius specified in a JSON file when a button is clicked?

I've developed a unique World Bubble Map that displays bubbles based on the geolocation of countries, with the size changing according to parameters selected from radio buttons. For example, when population is chosen, the bubble sizes adjust based on ...

Executing two asynchronous functions successfully

I encountered a scenario where I initiate the creation of a new user through an ajax call, and once the user is successfully created (server responds with 200), I immediately proceed to update the user using another ajax request. Currently, my approach in ...