"Utilizing Vue to bind data and manipulate it using $set

When using the set function to change the value of a variable that controls a class, I encounter an issue where the variable changes successfully but the class itself does not change.

The Vue file contains the following code:

<template>
    <li v-for="item in menu">
        <a href="" :class="{ 'show' : item.showNavItems }" 
                   @click="[$set(item, 'showNavItems', !item.showNavItems), toggleNavItems(item)]">{{ item.title }}</a>
    </li>
</template>

<script lang="ts">
    import { Component, Prop, Emit, Vue } from 'vue-property-decorator';

    @Component({})
    export default class SideNavigation extends Vue {
        @Prop({ default: [] }) menu!: []

        toggleNavItems(item: any) {
            console.log(item);
        }

        created() {
            console.log(this.menu);
        }
    }
</script>

The Menu variable is loaded from a twig file as shown below:

<side-navigation v-bind:menu="{{ global_data.getSideMenu|json_encode}}"></side-navigation>

Although I can see that the showNavItems variable changes after every click, the class 'show' does not change. When I moved this code to a fiddle (https://jsfiddle.net/7c3wLvah/), it appeared to be working fine. What could be causing the problem with my real component?

Answer №1

Make sure to include the class name "show" in your style sheet and remember to use square brackets for class binding as shown below:

<a href="javascript:void(0);" :class="[item.showNavItems ? 'show' : ''] " @click="[$set(item, 'showNavItems', !item.showNavItems), toggleNavItems(item)]"><span class="holder"><i :class="item.holder"></i></span>{{ item.title }}</a>

Answer №2

The 'menu' variable is declared as an array, not an object. According to the documentation, you should utilize the $set method for arrays using the syntax $set(arrayName, Index, newValue). In your scenario, it would look something like this:

<li v-for="(item, index) in menu">
    <a 
      :class="{ 'd-none' : !item.showNavItems }" 
      @click="$set(menu, index, {showNavItems: !item.showNavItems ,title: item.title},)"
    >
   {{ item.title }}
   </a>
</li>

(I also changed the .show class to .d-none because I believe it makes more sense :)). You can try out this solution on this JSFiddle.

Answer №3

My solution involved creating a new data variable that transforms into a Vue.js object once the data is transferred from the Twig file.

@Prop({ default: () => {} }) menuData!: []
menu: [] = this.menuData

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

Record audio without relying on Mediarecorder

I am combining two AudioBuffers to form a single one. I believe this can be done without using the MediaRecorder, as real-time recording is not required. This is my current approach: concatenateAudio(buffers: AudioBuffer[]): void { const totalLength ...

Guide to testing error throwing in error events with Jest

I am having an issue with a particular learning case. The code snippet below is what I am dealing with and I aim to test error throwing: export const someFunction = async () => { //... const fileReadStream = createReadStream(absoluteFilePath) .on(&a ...

An unexpected stats.js error occurred while attempting to apply custom styles to the map in AngularGoogleMaps,

My experience with Angular Google Maps has been mostly positive, except for one issue that I have encountered. When attempting to add styles to the map using the styles input attribute, I encounter an error: js?v=quarterly&callback=agmLazyMapsAPILoad ...

Nuxt 2.5 and higher do not recognize the definition of Global

After utilizing Nuxt 2.1 in my app, I proceeded to upgrade it gradually and everything was fine until Nuxt 2.4. However, starting from version 2.5 and above, production builds are breaking with an error stating global is not defined. The location of the e ...

Are there any specific events in PrimeNg's p-calendar that trigger when the time is changed?

In my project, I utilized PrimeNg v5.2.7 for the From Date and To Date fields. I implemented minDate validation on the To Date field. However, I encountered a scenario where if I select 30th Jan 2021 as the From Date and only adjust the time in the To Da ...

Creating test cases for a service that relies on a Repository<Entity> to consume another service

Having trouble creating tests for an auth.service that seems pretty straightforward from the title. However, every time I run the tests, I encounter this error: TypeError: Converting circular structure to JSON --> starting at object with cons ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

The back button function in vue-router appears to be inactive and unresponsive

Does the Vue Router in hash mode respond to the back button in the browser? I am currently using the latest package and have extensively researched this issue. I have come across reports of this bug but have not found any resolutions. If this is working a ...

Uh-oh, something went wrong unexpectedly: "A commit hash is necessary."

When I attempt to add eslint using this command with Vue CLI version 4.5.15: vue add eslint An error message is displayed: WARN There are uncommitted changes in the current repository, it's recommended to commit or stash them first. ? Still proceed ...

This context does not contain the expected object "this"

I seem to be losing the reference to the "This" object within the helper class in this particular structure, and I'm not sure why. When looking at the getAll method, the this object is currently pointing to the object housed within the servicesDict a ...

Stop additional properties from being added to a typescript interface when converting JSON strings

Currently, I am developing an extension for Arduino on VSCode and facing an issue with a section of my code. To load the project's configuration, I am accessing a .json file located in the .vscode folder. While ideally, the user should not manually ed ...

Vue multi-page application encounters compilation errors when attempting to include CSS within the <style> elements

Within my MPA app, I have integrated vue.js as a vital component. Below is a simple test setup: the relevant sections of my template .... <div id='app-basket-checkout'> <h1>Expecting Something Special</h1> </div> ... ...

Is there a way to package extra files along with `NodejsFunction` in Node.js?

I am looking to add another HTML file to the source code, like shown below. https://i.sstatic.net/OyxDM.png Here is my current code: const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', { runtime: lambd ...

tips for working with vueJs and properties file

Hey, I was wondering if there's a way to store commonly used values and properties in a file like YML or a property file... ...and then reference them in VueJS components? In Java, we have Spring which allows us to use YML and property file properti ...

When I try to load JSON data using the http.get() method in my Angular 2 template, it returns

I've encountered an issue while attempting to read and parse a local json file into a custom class I created. The problem arises when trying to access properties of the class, as it throws errors indicating that the class is either null or undefined. ...

"Integrating Vuetify into a single-spa Vue application: Step-by-step

vue 2.6.14 vuetify 2.6.9 What is the process for integrating vuetify into a vue application? I am attempting to import my project into another project as a microfrontend application, but encountering issues. Here are the steps I followed: Create-single- ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...

The Post method in Next.js API does not display any data on the specified endpoint

Whenever I attempt to send a POST request from my frontend within a Next.js project (using TypeScript), the JSON data I expect at my API endpoint does not appear. Instead, all I see is an empty hyperlink that leads nowhere. The code for my API is placed i ...

What is the process for overriding the module declaration for `*.svg` in Next.js?

The recent modification in Next.js (v11.0.x) has introduced new type definitions: For next-env.d.ts (regenerated at every build and not modifiable): /// <reference types="next" /> /// <reference types="next/types/global" /> ...

Unable to access property 'runnable' of null while running Jest test

After creating a new .spec file, I encountered an issue where the tests inside it are failing with the following error: TypeError: Cannot read property 'runnable' of null at ret (node_modules/selenium-webdriver/testing/index.js:175:25 ...