Creating reactivity in Data and Vuex: A step-by-step guide

Here is the code snippet:

<template>

  <div class="chart"
       v-bind:style="chartStyleObject">

  </div>

</template>

<script>

export default{

data () {
  return {

    chartStyleObject: {
      width: this.$store.state.chartStyleObject.width,
      height: this.$store.state.chartStyleObject.height,
      marginTop: this.$store.state.chartStyleObject.marginTop,
      marginRight: this.$store.state.chartStyleObject.marginRight,
      marginBottom: this.$store.state.chartStyleObject.marginBottom,
      marginLeft: this.$store.state.chartStyleObject.marginLeft,
    },
  },
}
}

And here is a repository example:

const axios = require("axios");
export const state = () => ({
  chartStyleObject: {
    height: '247px',
    width: '500px',
    marginTop: '15px',
    marginRight: '0px',
    marginBottom: '0px',
    marginLeft: '15px',
  },
});


export const mutations = {
    changeChartDraggableEventState (state, EventState) {
        state.chartDraggableEventState = EventState;
    },
    changeChartHeight (state, height) {
        state.chartStyleObject.height = height;
    },
    changeHeightWrapper (state, HeightWrapper) {
        state.chartStyleObject.HeightWrapper = HeightWrapper;
    },
    changeWidthWrapper (state, WidthWrapper) {
        state.chartStyleObject.WidthWrapper = WidthWrapper;
    },
    changeChartMarginLeft (state, MarginLeft) {
        state.chartStyleObject.marginLeft = MarginLeft;
    },
    changeChartMarginTop (state, MarginTop) {
        state.chartStyleObject.marginTop = MarginTop;
    },
};

The Issue:
After changing the state of the repository through mutations, the properties of the repository update correctly. However, the data properties that are linked to the same state properties do not update for some reason. (Even though the repository property was changed)

My query:
Why is this happening - shouldn't the data property be reactive just like the repository property? And what would be the best approach to solve this problem in this scenario? (manually updating all storage properties in the code seems inefficient.)

Answer №1

When you set the values in

chartStyleObject: {
  width: this.$store.state.chartStyleObject.width,          // here
  height: this.$store.state.chartStyleObject.height,
  marginTop: this.$store.state.chartStyleObject.marginTop,
  marginRight: this.$store.state.chartStyleObject.marginRight,
  marginBottom: this.$store.state.chartStyleObject.marginBottom,
  marginLeft: this.$store.state.chartStyleObject.marginLeft,
},

You are allocating values to the properties like width, height, etc. These values correspond to the current values of the state variables.

If you wish for the properties of chartStyleObject to automatically adjust with changes in the store's state, you can either directly map the state in the template or create a computed property:

export default {
    computed: {
      chartStyleObject() {
        return {
          width: this.$store.state.chartStyleObject.width,
          height: this.$store.state.chartStyleObject.height,
          marginTop: this.$store.state.chartStyleObject.marginTop,
          marginRight: this.$store.state.chartStyleObject.marginRight,
          marginBottom: this.$store.state.chartStyleObject.marginBottom,
          marginLeft: this.$store.state.chartStyleObject.marginLeft,
        };
      },
    },
}

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

Vuex - Managing dependencies within nested modules

I am facing a challenge in expressing a dependency between properties within my app's state using Vuex. Upon logging in, the user must select one of several workspaces to connect to. It is essential for the workspace to depend on the login status; ho ...

Transforming a <Class Component> into a <Stateless Functional Component> by implementing Hooks and integrating a callback function

I am currently in the process of transforming a Class Component into a Stateless Functional Component by utilizing the concept of React Hooks. My focus is on working with custom field components in react-jsonschema-form. You can find more information on c ...

Error: Trying to assign a value to null in the innerHTML property has resulted in an uncaught TypeError

I've been struggling with an issue in my code where the innerHTML is not updating the content inside the content_holder div. Any help would be greatly appreciated! Despite trying different methods and conducting extensive research, I haven't bee ...

How can I ensure that the HTML I retrieve with $http in Angular is displayed as actual HTML and not just plain text?

I've been struggling with this issue for quite some time. Essentially, I am using a $http.post method in Angular to send an email address and message to post.php. The post.php script then outputs text based on the result of the mail() function. Howev ...

WTForms can only submit the initial form

My blog page allows users to add their replies, which is working correctly. However, I am facing an issue with the edit feature - only the first form is submitting properly. For example, when I try to submit the second or third form, it always submits the ...

Clicking on the ng-repeat will trigger the ng-click event, which populates all the data using ng

I need help including an HTML page using ng-click within ng-repeat. However, it is currently loading all the content for every ng-repeat element. My specific requirement is to only bind(ng-include) the clicked element. Please see the attachment for m ...

The protection ensured by employing an extensive hash in the query string for the recognition of a changing document

I am currently developing a small web application that creates exercise program printouts. The concept is simple - a user like a personal trainer can craft an exercise regimen and send it to their client via email using a unique link. http://www.myurl ...

Generating a collection of items using a pre-existing array of items

Struggling to create an array of objects based on another array of objects. I attempted to use flatMap and then reduce, but encountered an issue when I tried to collect multiple statuses in one object. Below is what I have attempted and the desired result ...

Forwarding requests via middleware in next.js 13 AppDir: true

I am currently working on implementing a redirect feature in next.js 13 when the jwt back-end is not received. This is being done with the appdir activated. This is the code in my middleware.ts file: import { NextResponse } from 'next/server' im ...

UnhandledPromiseRejectionWarning when chaining functions in Node Express is a common issue that needs attention

Currently, I am refactoring a Node Endpoint to handle two tasks: Verify if the user exists Add the user to the database controller.js exports.signup = (req, res) => { methods.checkUser('email', req.body.email) .then(methods.addUser(r ...

A guide to effortlessly importing JSON data with Svelte

During my recent testing, I have successfully utilized the below code to work with a component: <script> import x from "/path/to/x.json" </script> This code snippet effectively loads the json file into the variable x. Now my objecti ...

React Native failing to display images sourced from a URI

I have thoroughly reviewed all responses to similar inquiries, but none of them seem to tackle my specific problem. Despite following all the recommended steps for success, as evident in my code snippet below and the accompanying screenshot, I continue to ...

Tips for effectively loading data of a specific user or event into a bootstrap modal in Laravel using AJAX

I'm having some trouble loading Event data into my bootstrap modal in Laravel. This is all new to me as I'm just getting started with AJAX. Can someone please take a look at what I've done so far? Modal Template <div class="modal fa ...

Unraveling the mysteries of interpreting the jsben.ch benchmark results

After testing three fibonacci algorithms on jsben.ch, it's clear that the first one is the fastest and even received an award icon: https://i.sstatic.net/ilfDz.png However, I'm curious about the numbers next to the code block results. What do t ...

Struggling with sending data to a modal in AngularJS?

I am dealing with the following code snippet $scope.currentTask = undefined; $scope.openModal = function (task, size, parentSelector) { var parentElem = parentSelector ? angular.element($document[0].querySelector('.modal-d ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

Tips for postponing the appearance of the background image within a div tag

Check out my fiddle here. I am looking to create an effect where the "background-image:" in the CSS loads fully and displays after a 3-second delay with a quick fade-in effect. Until then, the entire div should be in black color. How can this be achie ...

Executing Javascript Function Once ASP.Net Server Processing Finishes

If I have a basic web application built in asp.net/vb.net, with a single button on the web page. When this button is clicked, it triggers some functionality in the code behind. What I want to achieve is to run a JavaScript function after the page reloads, ...

variety of provider setups available in Angular

Trying to learn Angular from various online sources can be quite confusing, as different people use different patterns when writing functions. Can someone please explain the .provider concept in Angular? I have experimented with the .provider method using ...

There appears to be an issue with the express Router when trying to access the '/page' route

Currently, I am in the process of creating a basic express routing system while utilizing vanilla HTML for the front-end. index.js const express = require('express'), bodyParser = require('body-parser'), serverle ...