Guide to implementing dynamic conditional rendering in Vue.js loops (utilizing v-if within v-for)

I am currently working on a table component in a .vue file where I want to display icons based on the direction of the order clicked.

For example:

<th v-for="(column, index) in columns" :key="index" @click="sort( index )">
                <span>{{ column.label }}
                    <i v-if="column.dir == 'desc'" class="fa fa-sort-down"></i>
                    <i v-else class="fa fa-sort-up"></i>
                </span>

The above snippet represents the header layout, and here is an example of my default column object:

data().....
  columns: [ 
            {
                label: '#',
                order: false,
                search: false,
                column: 'id',
                dir: 'desc'
            },
            {
                label: 'Username',
                order: true,
                search: true,
                column: 'username',
                dir: 'desc'
            }]

When sorting, I update the clicked column using the sort method.

var col = this.columns[column];
col.dir = ( col.dir == 'desc' ) ? 'asc' : 'desc';

this.$set(this.columns, index, col);

Vue.set(this.columns, index, col);

Also
this.$nextTick(function() {
  columns[index].dir = ( columns[index].dir == 'desc' ) ? 'asc' : 'desc';
});

Although I can see the updated value in the Vue dev tool, the reactivity does not reflect back in the main columns object, and the view fails to update accordingly.

I might be missing some key concept here, so any guidance or assistance would be highly appreciated. Thank you

UPDATE.....

Many thanks for the assistance provided. It turns out that font-awesome was altering the tags in the DOM and replacing them with an SVG, which caused Vue.js to have trouble recognizing them.

Despite this issue, I will still select a helpful answer from below.

Answer №1

I implemented most of your code and it seems to be working smoothly... https://jsfiddle.net/aj2nf6cw/

Is it possible that the issue lies in using var col = this.columns[column]; instead of var col = this.columns[index];?

The use of var is acceptable as it will automatically point to this.columns[index] because it's an object.

By the way, I don't think you've correctly utilized Vue.set. Check out: https://v2.vuejs.org/v2/api/#Vue-set. If you were to incorporate it, the format should be

Vue.set(this.columns[index], 'dir', 'asc');
, but in your case, it's not necessary since your data is already reactive.

Answer №2

The reason why your current approach is not functioning is due to the fact that you are creating a variable inside the sort method which does not have Vue's observability like this.columns. I recommend checking out this example code snippet for a working solution.

To fix this issue, you will need to make a modification in the sort method as shown below:

sort(index){
   this.columns[index].dir = (this.columns[index].dir == 'desc') ? 'asc' : 'desc'; 
}

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

Combining Json attributes in Jquery Grouping

My task is to group the displays by sectors, but I couldn't find a method in JSON to achieve this. Below is the code snippet: $(function displays(){ var url = '{% url get_displays %}'; $.getJSON(url, function(data) { var sidebar = ...

Iterate through the loop to add data to the table

Looking for a way to append table data stored in local storage, I attempted to use a loop to add cells while changing the numbers based on row counts. Here is my JavaScript code snippet: $(function() { $("#loadTask").change(function() { var ta ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

gulp.watch executes tasks without following a specific sequence

Objective Develop a gulp.watch task to execute other tasks in a specific sequence Why this is unique While many have referred me to How to run Gulp tasks sequentially one after the other, my query differs as it pertains to using gulp.watch instead of gu ...

How can I hover over multiple cells in a table?

Is there a way to change the color of multiple adjacent cells when hovering over one cell, and can this be done dynamically (so the number of adjacent cells that change color can vary)? Here is the code snippet: I'm using React to create a table wit ...

Resolving Route Problems in Node.js with Express

Currently, I am in the process of developing a website using Express and NodeJS. One issue that I have encountered is related to routing. In my app.js file, I have defined a route that expects a parameter like so: app.get(['/purchase/:purchaseID&apos ...

Struggling with D3.js Angular CLI where Scope disappears within the tick() function?

Hey everyone, I'm currently in the process of incorporating a D3 visualization network graph into an Angular CLI project (http://bl.ocks.org/mbostock/1153292) using the ng2-nvd3 component. Here's the Angular component: import { Component, OnIn ...

Facing a dilemma: Javascript not updating HTML image source

I am facing an issue while attempting to modify the source of my HTML image element. Despite using document.getElementId('image') in my code, I am unable to make it work as intended. Surprisingly, there are no errors displayed. Interestingly, whe ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...

Solving the 'never' type issue in Vue3 and TypeScript for an empty array reference

I am currently in the process of migrating a component from an old Vue project that relies solely on JavaScript to a TypeScript/Vue project, and I have encountered some obstacles along the way. <script lang="ts"> import { computed, ref } fr ...

initiating an event when the page is loaded

Uncertain if this could be considered an anti-pattern, I am hoping someone can provide insight on a better approach. I have attached a resize event to the window and also want the same code to execute on load. Is this the proper way to achieve this? angu ...

Extension for Chrome

My goal is to develop a Chrome extension that, when a specific button in the extension is clicked, will highlight the current tab. However, I'm encountering some challenges. Currently, I have document.getElementById("button").addEventListen ...

Exploring JQuery and JavaScript for loop guide

Currently working on a small application where users are required to input information, and I am implementing text hints in the input fields. However, I have encountered an issue when using a for loop in my code. Oddly enough, the text hints display corre ...

Vue.js and Element UI combine to display a custom HTML message in a MessageBox component

I am currently utilizing vue-js 2.3 along with element-ui. Specifically, my question pertains to the MessageBox component and you can access the documentation for it here Issue I am interested in incorporating an html message within the MessageBox. More ...

Striving to design an event planner with the datepicker feature in javascript

Currently, I am integrating a javascript datepicker into my project to facilitate displaying a calendar and selecting a date for adding/viewing/editing events on that specific date. On my view, the datepicker calender is displayed within a div element. & ...

Vuejs - Trouble with Component Rendering on the Screen

I'm currently working on developing a Vue application for monitoring and managing budgets. I have a BudgetItems component that I intend to display in the /budget route. Although all other components and raw HTML are successfully rendering, this specif ...

Unlocking the secrets of obtaining post values using Body-parser in your Express Node.js application

Currently, I am utilizing Express version 4.11.1 and Body-parser version 1.11.0 in my project. However, upon running the code snippet below, I encountered the following output: I am seeking suggestions on how to retrieve the form value. Output {} serve ...

Retrieve the content within a div tag

Hey there, I have a div set up as follows: <div>1+1</div> I'm looking to send this '1+1' value over to my javascript code and calculate it to get '2'. Appreciate any help in advance! ...

Toggle the active class on the parent element when it is clicked

I'm encountering a problem with my JavaScript - attempting to make this function properly. Firstly, here is the desired functionality: 1.) Add or remove the 'active' class from the parent element when clicked 2.) When clicking inside the ...

My JavaScript code is not triggering during the page load. Could this be related to .net

I've been attempting to trigger a JavaScript function upon the refresh of an update panel, but for some reason it's not working. Oddly enough, I'm using the same approach that has worked for other functions. In C#, this is what I have in th ...