Changes have been made to the Vue object, however, it does not trigger a re-render

Whenever I hit the right arrow key, it adjusts the object without re-rendering it :

<div class="map">
   <div class="map-page" tabindex="0"  @keyup.arrow-keys="show"  ref="mapPage">
     <template  v-for="mapRow in mapMatrix">
       <div  v-for="cell in mapRow" @click="(cell.view === '1') ? showAlert() : false " v-bind:class="['map-cell',{'cell-active' : cell.active}]">
              {{cell.view}}
       </div>
     </template>
   </div>
<div>

Using key pressed(@keyup.arrow-keys="show") to alter the active cell.

show: function (event) {
        if(event.keyCode === 39){
          if (this.selectedCellId !== CELL_NUMBER){
            this.moveRight();
          }
        }
    },
moveRight: function(){
      this.$set(this.mapMatrix[this.selectedRowId][this.selectedCellId],'active',false);
      this.selectedCellId++;
      this.$set(this.mapMatrix[this.selectedRowId][this.selectedCellId],'active',true);
    },

It worked perfectly with the static object:


 mapMatrix: {
        0 : {
            0 : {
                  "view" : "-1",
                  "available" : true,
                  "active": false
            },
            1 : {
                  "view" : "1",
                  "available" : true,
                  "active": false
            },
            2 : {
              "view" : "1",
              "available" : true,
              "active": false
            },

          },
...
}

However, it doesn't work properly with:

fillMatrix: function(){
      var i;
      var g;
      for(i = 0; i <= CELL_NUMBER; i++){
          this.mapMatrix[i] = {};
          for(g = 0; g <= CELL_NUMBER; g++){
            var view = this.setVeiw(g);
            this.mapMatrix[i][g] =
              {
                    "view" : view,
                    "available" : true,
                    "active": false
              };
        }
      }
    }

It changes the object correctly, but there is no response on HTML render. What could be causing this difference?

Answer №1

It appears that the way you are constructing the matrix object may not function correctly with Vue, as it might not become reactive. It is recommended to refer to the Change Detection Caveats.

To ensure reactivity, consider using this.$set during matrix construction or create the matrix in a local variable first and then assign it to this.mapMatrix.

You can follow this approach:

fillMatrix() {
  // Create a new non-reactive object
  const mapMatrix = {};

  for (let i = 0; i <= CELL_NUMBER; i++) {
    mapMatrix[i] = {};

    for(let g = 0; g <= CELL_NUMBER; g++) {
      mapMatrix[i][g] = {
        view: this.setView(g),
        available: true,
        active: false,
      };
    }
  }
  
  // By assigning the new mapMatrix object to this.mapMatrix, Vue will detect it
  // and make the object reactive
  this.mapMatrix = mapMatrix;
}

Answer №2

Consider updating the object-fill function to a more dynamic approach, as suggested in the @jcbdrn comment:

fillMatrix: function(){
      var i;
      var g;
      for(i = 0; i <= CELL_NUMBER; i++){
          this.$set(this.mapMatrix,i,{});
          for(g = 0; g <= CELL_NUMBER; g++){
            var view = this.setVeiw(g);
             this.$set(this.mapMatrix[i],g,
               {
                   "view" : view,
                   "available" : true,
                   "active": false
             }
           );

        }
      }
    },

Implementing this change effectively resolved the issue at hand.

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

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

What is the best way to retrieve the height of the parent element in my specific situation

I am facing an issue in my directive where I need to access the height of the parent element. Here is a snippet of my code: (function(window, angular) { var app = angular.module('myApp'); app.directive('testElem', [ fu ...

Tips for utilizing a variable from a function in one file within a function in another file

Having trouble using the variable counter from one function in a different file? In the first function, I defined counter without using "var" thinking it would make it a global variable. But for some reason, it doesn't seem to work. Help needed! //fun ...

What causes the difference between object[key] and Object.key in JavaScript?

After running the following code snippet, I observed that "typeof object[key]" is displaying as a number while "typeof object.key" is showing undefined. Can anyone explain why this unusual behavior is occurring? var object = {a:3,b:4}; for (var key in o ...

Firebase onCall function is executing properly, however, it is only delivering {data: null} as the

I am facing an issue with my cloud function where everything runs smoothly until I attempt to return a response back to the front-end. Despite successfully modifying databases, the final log points D and G still show {data:null} as the output. I have a fe ...

Building a dynamic and fast Vite project using "lit-ts" to create a visually appealing static website

I recently put together a project using Vite Lit Element Typescript and everything seemed to be running smoothly on the development server. However, when I tried running npm run build, only the compiled JS file was outputted to the /dist folder without any ...

Can someone please help me convert this jQuery code into vanilla JavaScript?

My Cordova app has an email sending function that utilizes jQuery. During debugging, the ajax function works perfectly in my browser, but once I build the app and test it on my phone, it stops working. I encountered a similar issue before, which was resolv ...

Utilizing Node Js and Socket.Io to develop a cutting-edge bot

Is it possible to run JavaScript with Node.js without launching Google Chrome from various proxies? Can someone provide a sample code for this task? For example, you can find a similar project here: https://github.com/huytd/agar.io-clone Another project c ...

When using a wildcard router in Node.js/Express.js, the static router may not be recognized

While using this specific route along with my other routes, I encounter an issue with serving static files: var public_dir = path.join(__dirname, 'public'); app.use('/public', express.static(public_dir)); However, when I add the follo ...

What setting should I adjust in order to modify the color in question?

Looking to Customize Radar Chart Highlighted Line Colors I am currently working on a Radar Chart and I am trying to figure out which property needs to be edited in order to change the color of the highlighted lines. I have already attempted to modify the ...

Unity3D: Troubleshooting a Code Issue

Encountering an issue with my code and struggling to find a solution. I've tried moving my c# script up to the standard assets folder as suggested in my research but it didn't resolve the problem. Any assistance would be greatly appreciated! Than ...

What is the best way to target the specific DIV using a jQuery selector?

My dynamic div is filled with other divs... <div id="wrapper"> </div> //javascript for(//lots of times){ var d = document.cloneNode('divModel'); d.foo = {//a lot of stuff }; document.getChildById('wrapper').append ...

Building Dynamic Columns within a react.js Environment

Can anyone help me with creating a dynamic column in react.js? I've already managed to do it with static columns, but now I want to make them dynamic. Take a look at my code below and please provide suggestions. import React from 'react'; i ...

Instructions for manipulating and displaying a source array from a child component using Vue

I have a parent component with an array that I display in the template. My goal is to click on a link that uses vue-router with a dynamic id attribute, and then open a new component displaying only the element of the array that corresponds to that id. Howe ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

Inserting items into an array based on the user-specified quantity

Suppose I have an array with 8 elements. If the user enters a number greater than the length of the array, how can I dynamically add the remaining items to the list? For example: If my array length is 8 and the user enters 15, how can I add 7 items to th ...

How can Sequelize handle multiple foreign keys - whether it be for one-to-many relationships or many-to-many relationships

I'm working on a project with two tables: users and alerts. Users should have the ability to upvote and downvote on alerts. Here are the model definitions: Alert module.exports = function(sequelize, DataTypes) { var Alert = sequelize.define("al ...

Avoid updating the input from ng-model while it is being edited

There are times when my model.field can be altered by both user input into an input field and by other functions running in the background. However, I want to handle situations where changes made by the user take precedence over modifications made by those ...

Is it possible to integrate SVGs into Nuxt with Vue.js without the need for importation?

I am currently working with Nuxt and Vue.js, attempting to display some SVG images on the webpage. However, I keep encountering the following issue: https://i.sstatic.net/lJ3dc.png Ignore the pink color, as it comes from another element. I have tried ins ...

Retrieve an item from a table in VUE upon clicking

I am currently using Vue Bootstrap and I want to be able to access the item when a row in the table is clicked. I have set up a table and a clickmeRow method to handle the action on the clicked item. <b-table-lite hover :items="it ...