Unusual reactivity glitch in Vue.js

I am at a loss here and could really use some troubleshooting assistance.

Out of nowhere, I encountered reactivity issues after transferring code from my main/root App.vue file to a Home.vue "view" file.

Let's look at the original template syntax in my App.vue:

  <div id="app">
    <Header15 />
    <router-view />
    <UtilsBar />
    <Footer15 />
  </div>
</template>

The problematic portion of code defined in my Home.vue file is as follows:

<ul class="filter-list">
  <li class="filter-list__litem" v-for="theme in themeFilterButtons" :key="theme.id">
    <a class="filter-list__link" :class="{ 'on': theme.isActive }" :href="'#'+theme.id" @click.prevent="onFilterSelect('theme', theme.id)">
      {{ theme.isActive }}<br />
      {{ theme.text }}
    </a>
  </li>

themeFilterButtons is a computed array of objects.

computed: {
  themeFilterButtons() {
    return this.filters.themes.map((theme) => {
      return { ...theme, isActive: false };
    });
  }
}

The new array references an array called themes from my filters object; it's structured in my data like this:

data() {
  return {
    filters: {
      themes: [
        { id: 113, text: 'First World War' },
        { id: 214, text: 'Second World War' }
      ]
    }
  }
}

The onFilterSelect method linked to the click event eventually triggers another method, filterBtnSelToggle, which handles toggling a selected class (.on) by toggling the isActive property on the object.

To troubleshoot, I attempted to simply set the isActive property on the first array index to true. Despite setting it initially as false, clicking any button fails to change the value to true. The template view, using v-for, remains unchanged no matter how I adjust that value. Various attempts were made but failed to update the markup.

onFilterSelect(cat, id) {
  // Attempting to set isActive: true on the initial array item.
  this.themeFilterButtons[0].isActive = true; // < No effect.
  this.$set(this.themeFilterButtons[0], 'isActive', true); // < Still does not work.
  console.log('this.themeFilterButtons[0].isActive'); // Returns true.
}

Expected values are logged to the console, but the issue lies in updating the template (markup).

This functionality was previously operational and continues to function correctly when the logic is moved back to the primary App.vue file...

Any guidance would be greatly appreciated!

Answer №1

When faced with this scenario, the computed property relies on this.filters.themes and you consistently set isActiv false. Therefore, setting themeFilterButtons as a data property will allow it to function properly.

  // Remove computed code block and set themeFilterButtons property in data 
  mounted() {
    this.themeFilterButtons = this.filters.themes.map((theme) => {
      return { ...theme, isActive: false };
    });
  },

Answer №2

Consider utilizing the getter setter computed property.

computed: {
  themeFilterButtons: {
    get () {
      return this.filters.themes.map((theme) => {
        return { ...theme, isActive: false };
      });
    }
    set (val) {
      this.filters = val
    }
  }
}

Alternatively, a more efficient approach would be initializing isActive within the data section initially.

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

Utilize the search component multiple times within a single template in Vue.js

I have a regular search input that searches and displays results effectively. Now, I need to duplicate this search input and reuse it within the same component. <input class="search ml-2" type="search" placeholder="Search" v-model="search"> Here is ...

Are your Promises.all functions executing at the incorrect timing?

I can't seem to understand why Promise.all is not working as expected. Even though the log shows that data for "Streak" and "Last Activity" is successfully retrieved towards the end, I want Promise.all to fetch the data only when everything is filled ...

Exploring the functionality of setAttribute method in JavaScript

Snippet: activeCell.onclick = function() { console.log(element); element.value = this.value; console.log(element.value); console.log(element); }; Imagine activeCell as a span with value = "678", while element is represented by a simple in ...

Finding it difficult to grasp the concept of enabling CORS through an ajax request

I'm struggling to figure out how to enable CORS while using Ajax to send data to a remote server on a different domain. Despite researching extensively and reading numerous Stackoverflow threads, I can't seem to make sense of it all. I understand ...

Generating a JSON tree hierarchy from an array of nested objects

I have a JSON array of objects that looks like this: [{ "vehicleid": 3, "name": "Teste2VDD", "brand": "Scania", "model": "6x2", "class": "class1", "region": "Curitiba", "customer": "Cliente A", "customerid": 1 }, { "veh ...

JSON Serialization of numeric data types

It came to my attention that the website generates the same Base64 string for payloads containing numerical values written in different notations. An interesting example is the output for these two payloads: { "value": 0.000001 } { "val ...

Tips for successfully passing PHP variables to a JavaScript function

Having trouble passing the selected values of two comboboxes to another PHP file using AJAX. How can I pass both values in one function? <script> function showUser(str,str2) { if (str == "" || str2 =="") { document.getElementById("tx ...

Displaying child properties in a functional ReactJS component

React version 0.14 introduces the concept of pure functional components, ensuring that the same input always results in the same output. Props are passed as function arguments. // Using ES6 arrow functions with implicit return: const PureComponent = ({url ...

Make the adjustment from an H1 tag to an H2 tag with the help of

I need assistance with changing the HTML code from using an <h1> tag to a <h3> tag, using Vanilla JavaScript. Here is the code snippet in question: <h1 class="price-heading ult-responsive cust-headformat" data-ultimate-target=" ...

Is there a way to display a success message once the button has been activated?

<template> <div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Enter ...

NextJs issue: Your `getStaticProps` function failed to return an object

I am currently developing a web application using NextJs. On one of the pages, I am trying to make an API call to fetch data and display it. However, during compilation, I encountered an error. The specific error message is: Error: Your `getStaticProps` f ...

Creating interconnected circles with lines utilizing canvas

I am currently utilizing the canvas tag to generate circles on a world map image. My objective is to link these multiple circles with lines using the Canvas tag. Although I have successfully drawn the circles, I am facing difficulty in drawing the connecti ...

Tips for resolving the issue of invalid functions as a child component in React

When I call a function that returns HTML code, everything works fine until I try to pass a parameter in. At that point, I receive an error saying "Functions are not valid as a React child." The issue is that I need to access the props from this function. T ...

The issue with Angular 1.6 not displaying the scope value in the template

Hey there! I'm currently working on index.html Here's the code snippet from before: <body ng-app="MainController"> <div class="page page-base {{ pageClass }}" ng-view> </div> </div> Then, I made changes by ass ...

As I enlarge the font size, the border around the div also expands

Can someone explain why the size of the div border increases along with the font size? If you'd like to see an example, check out this link to a jsFiddle: LINK TO JS FIDDLE: http://jsfiddle.net/krishna22211/m14qms52 ...

What is the process for customizing the arrow of a <select> dropdown menu exclusively?

Here is the code for a dropdown menu: <select id="dropdown"> <option value="">Go to page...</option> <option value="http://stackoverflow.com">CSS-Tricks</option> <option valu ...

What is the best way to execute a JavaScript function when the onSelect event of a jQuery datepicker is

Is there anyone who can assist me? I am currently working with a JavaScript function: function updateAb(param){ some manipulation } I also have a datepicker jQuery plugin that I am using for the onSelect event, like so: $( ".datepicker").datepicker({onS ...

Firefoxx effortlessly glides divs across the screen as if they were images

Below is the HTML, CSS, and JavaScript code all in one document for testing: <style type="text/css"> #slider_container { width: 200px; height: 30px; background-color: red; display:block; } #slider { width: 20px; height: 30px ...

Struggling to run two separate single page applications concurrently on a single server with nginx

UPDATE: I have made revisions to this post in order to provide a clearer explanation of the issue. The initial post has been replaced with this updated version. We are dealing with two single-page applications that must be accessible from the same domain ...

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...