Verifying updates in the watchlist once data has been initialized upon mounting

When trying to edit a component, the data is loaded with mounted in the following way:

  mounted () {
    var sectionKey = this.$store.getters.getCurrentEditionKey
    this.table = _.clone(this.$store.getters.getDocumentAttributes[sectionKey])
    this.table.tableGrid = _.clone(this.$store.getters.getDocumentAttributes[sectionKey].tableGrid)
    this.entered = true
  },

In order to track changes on the component, I modify the value of this.entered. I use a watcher to monitor when elements are loaded.

watch: {
    'table.rows': function (val, oldValue) {
      if (this.entered === true) {
        if (val > oldValue) {
          this.table.tableGrid.push([''])
        } else if (val < oldValue) {
          this.table.tableGrid.splice(this.table.tableGrid.length - 1, 1)
        }
      }
    },
    'table.cols': function (val, oldValue) {
      if (this.entered === true) {
        if (val > oldValue) {
          for (var i = 0; i < this.table.rows; i++) {
            this.table.tableGrid[i].push('')
          }
        } else if (val < oldValue) {
          for (var j = 0; j < this.table.rows; j++) {
            this.table.tableGrid[j].splice(this.table.tableGrid[j].length - 1, 1)
          }
        }
      }
    }

 data () {
    return {
      entered: false,
      table: {
        rows: 1,
        cols: 1,
        insert: 1,
        key: 'Table',
        tableStyle: 1,
        caption: '',
        hasCaption: true,
        hasHeader: true,
        tableGrid: [
          ['']
        ]
      }
    }
  },

The cols and rows values are obtained as follows to rebuild the table when they change:

tableRows () {
  return parseInt(this.table.rows)
},
tableCols () {
  return parseInt(this.table.cols)
}

I am tracking the table's cols and rows, but the watcher triggers before mounted. Any tips on how to handle this situation?

Answer №1

Here is a sample code snippet that showcases the key features you are attempting to utilize, and it performs as intended. You can utilize this as a foundation to troubleshoot your issue.

var vm = new Vue({
  el: '#app',
  data: {
    data: {
      rows: 1
    },
    entered: false
  },
  mounted() {
    var self = this;
    setTimeout(function() {
      self.data = {
        rows: 10
      };
      self.entered = true;
    }, 1200);
  },
  watch: {
    'data.rows': function(newValue) {
      if (this.entered) {
        console.log("Rows now", newValue);
      } else {
        console.log("Not entered!");
      }
    }
  }
});

setInterval(function() {
  ++vm.data.rows;
}, 800);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
</div>

As you set this.table in the data section, it acts as a dynamic variable allowing you to update it as required:

this.table = _.clone(this.$store.getters.getDocumentAttributes[sectionKey]);

The crucial point to consider is whether this.table.tableGrid is also dynamic. If it originates from the previous clone, then it will be responsive; otherwise, not. If unsure, modify this segment:

this.table.tableGrid = _.clone(this.$store.getters.getDocumentAttributes[sectionKey].tableGrid);

to

this.$set(this.table, 'tableGrid', _.clone(this.$store.getters.getDocumentAttributes[sectionKey].tableGrid));

(It appears that the initial clone should have encompassed the entire copy operation.)

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

Why is it necessary to type in localhost in the address bar when using node.js and socket.io instead of simply opening the client.html file directly?

I am intrigued by this topic. My suspicion is that it may be related to the temporary file created by socket.io, but I'm struggling to fully understand it... ...

Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript. Currently, I am faced with the challenge of having to create separate div elements each time I want to add n ...

Guide to creating "bidirectional data binding" in Vue

I have a child component that is responsible for uploading a photo. The uploaded photo is assigned to the child component's data called "photo". I need to connect the parent data called "file" with the child data called "photo". And whenever "photo" i ...

What is the best way to manage the loading and unloading of JavaScript within dynamically loaded partial pages?

Utilizing jQuery and history.js, I manage seamless transitions between partial pages to prevent entire document reloads. Some of these partial pages include unique javascript files. Despite successful page transitions, remnants of executed javascript linge ...

Vue loading all the pieces in one go on the initial request

Currently, I am delving into the world of Vue and just started learning about routing. After setting up a template project using vue/cli with an initial router configuration, I came across this Router code: export default new Router({ mode: 'histor ...

Add a new class to an element located in a separate div using JavaScript

$(document).ready(function() { $('.btn').click(function() { $(this).parent().addClass('show'); }); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div clas ...

Troubleshooting issues with Ajax and Jena

Whenever I attempt to utilize AJAX to call Jena in my servlet, I encounter this error: java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apa ...

The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript: var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800 ...

JavaScript Multiplicative Persistence Problem Resolved by Implementing Efficient Solution that Executes in a Timely

I am currently facing an issue with the following problem: Your task is to create a function called persistence, which takes a positive parameter num and calculates its multiplicative persistence. Multiplicative persistence refers to the number of times y ...

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

Changing values in object using Mongoose in MongoDB

Currently, I have a basic collection stored in MongoDB using Mongoose. My users model consists of a single field of type object, and I am looking to dynamically modify this object. However, despite my attempts using findByIdAndUpdate(), findById, findOne( ...

Difficulty closing Modal Popup when multiple Modals are displayed simultaneously

I am facing a challenge with transitioning between modal screens When the button on the screen is clicked, Modal1 opens: $modal.open({ templateUrl: 'abc.html', controller: 'abcCtrl', size: 'lg', scope: $scope ...

What is the best method for selecting or deselecting all checkboxes except for one using a single checkbox in angularjs

$scope.checkAll = function() { if ($scope.selectedAll) { $scope.selectedAll = true; } else { $scope.selectedAll = false; } angular.forEach($scope.MyProducts, function(item) { item.Selected = $scope.selectedAll; }); /*});*/ } <di ...

Display an iframe using React in multiple areas across the app with the same state

Within my React scenario, we display a BI dashboard using an iframe on the page, allowing users to interact with the frame and potentially filter the BI data. I've developed a feature that enables this iframe to expand into a full-screen dialog for en ...

Having trouble closing the phonegap application using the Back Button on an Android device

I've encountered an issue with my code for exiting the application. It works perfectly the first time, but if I navigate to other screens and then return to the screen where I want to close the app, it doesn't work. <script type="text/javascr ...

Obtain the current date from the data source to utilize in a Vuetify component

I am looking to incorporate a vuetify calendar that highlights today's date. How can I retrieve the current date and assign it as a variable in the data? Below is an example of calendar code from the Vuetify webpage for reference. This particular exa ...

Generate an array of responses within a child component and then send this array to the parent component using Vue.js 2

Currently, I am in the process of creating a survey using Vue 2. My goal is to construct and emit the answers array to a parent component named Evaluation. You can view the structure of this array here: https://pastebin.com/rLEUh56a Within my project, the ...

Setting up a chat feature in a Laravel application: A step-by-step guide

Looking to Enhance My Web-Application I have been working on a web-application that utilizes: Laravel for the back-end Angular for the front-end. Milestone Achieved! I successfully implemented the entire user authentication process including: User Aut ...

steps to iterate through an array or object in javascript

Hello, I am facing an issue while trying to loop through an array or object. Can someone help me out? Are arrays and objects different when it comes to using foreach? function fetchData() { fetch("https://covid-193.p.rapidapi.com/statistics", { ...

Creating a <Box /> component in MaterialUI with styled components is a great way to customize the design and layout of your

@material-ui/styles offers a different way to customize default styles: import React from 'react'; import Box from '@material-ui/core/Box'; import { styled } from '@material-ui/core/styles'; const StyledBox = styled(Box)({ ...