Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter only to that specific field. However, the current code results in NaN for every field.

<tr v-for="record in records" @dblClick="readRecord(record)">
  <td v-for="column in columns">
    {{ _.startsWith(record[column.id], 'd') ? record[column.id] | humanize : column.id; }}
  </td>
</tr>

Answer №1

It might be a good idea to refactor the code in the view into a separate method, especially considering that filters are now deprecated (update: only filters in directives are deprecated).

new Vue({
  el: '#app',
  data: {
    columns: [{
      id: '1'
    }, {
      id: '2'
    }],
    record: {
      2: 'dthing'
    }
  },
  methods: {
    displayCol: function(col) {
      if (s.startsWith(this.record[col.id], 'd')) {
        return this.humanize(this.record[col.id]);
      }
      return col.id;
    },
    humanize: function(recVal) {
      return `HUM${recVal}`;
    }
  }
});
<!--script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script-->
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.min.js"></script>
<div id="app">
  <div v-for="column in columns">
    {{displayCol(column)}}
  </div>
</div>

Answer №2

Here is where you can invoke your filter: this.$options.filters.humanize

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

Suggestions for improving the way time durations are calculated using jQuery

Although I have some experience with jQuery and javascript, I am still relatively new to the world of programming. I can write basic scripts, but I feel that there is room for improvement in optimizing some of my code. Specifically, I'm working on a p ...

JavaScript button is not functioning properly to increase or decrease the value in the input field

I'm facing an issue with the javascript increase/decrease buttons on my website. When I assign my JS variable as the class name of the input field, pressing the button results in all input fields being affected simultaneously: https://i.stack.imgur.c ...

Can you explain how to convert a 32-bit floating point number from a Buffer to a JSON string in NodeJS while maintaining the original precision?

Given a buffer with single precision float numbers (32 bits, little endian), the goal is to create a JSON string holding those numbers while maintaining their original values without any loss of precision. The challenge lies in the fact that when a value ...

Index is bound to data using a specific syntax for data binding

Having trouble with a syntax issue that is likely simple. I am attempting to replace the '1' in 'play1' with the v-for index. <tr v-for="index in 5"> <td>{{player1.round1['play' + index]}}</td> <td> ...

The dimensions of the box are not predetermined by the size of the photo

I'm attempting to develop a photo gallery that emulates the style of (using the Unsplash API -> ) However, the size of the container box does not adjust properly with the photos. https://i.sstatic.net/1PAQF.jpg <div className="imageGrid_ ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

What steps can be taken to resolve the "npm ERR! code ELIFECYCLE" error in a React application?

After attempting to start my React app with npm start, an error occurred : $ npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b3d2a212b3c0f7f617e617f">[email protected]</a> start C:\Users&bso ...

Issue encountered while executing npm command: "Module 'npmlog' not found"

Today marks the beginning of my first job, and as I was setting up my development environment on my Mac (OSX) by updating node and npm, something went awry. Whenever I attempt to use npm in my command line (npm init, npm install, etc.), I am confronted wit ...

Create a new chart using completely unique information

I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modif ...

changing the RadioButtonList to preselect a default value

On a page, I have a pre-existing RadioButtonList where I want to make the second button checked by default instead of the first one. Since I am unable to edit the original control directly, it seems like I might need to achieve this using javascript on th ...

Tips for sending images as properties in an array of objects in React

I've been experimenting with various methods to display a background image underneath the "box" in styled components. How can I pass an image as a prop into the background image of the box with the image stored in the array of objects? I'm unsure ...

Updating a model within an ng-repeat directive from external sources

Within my controller, there is a repeater where each item has its own unique status: <div ng-controller="..."> <div ng-repeat"...">{{status}}</div> </div> Currently, changing the status within the repeater by using status = &apo ...

Tips for refreshing a page in Vue.js

I am facing an issue with updating a table on my page after deleting a row. Each row in the table has a delete button and I have tried using window.location.reload() but it didn't work. </va-card> <br/> <va-card > ...

Expanding a JSON data structure into a list of items

In my Angular service script, I am fetching customer data from a MongoDB database using Django: getConsumersMongodb(): Observable<any> { return this.httpClient.get(`${this.baseMongodbApiUrl}`); } The returned dictionary looks like this: { &q ...

Socket.io integration with JWT authentication

Having some trouble establishing a connection with JWT. It's not returning anything and I'm not very familiar with JWT so not sure where I might be going wrong. Unable to do anything on localhost:4000 due to the lack of connection. Any suggestio ...

individualized django models field for each user

Is it possible to create a boolean field in the post model to track if a user has liked a post? This field should only be changed by the respective user and not affect others. For example, if user 1 likes a post, it should show as true only for that user ...

What is the best way to create a loop within a JavaScript function?

I'm having some trouble with looping inside a function. It seems like my looping is not working properly and I need help fixing it, along with suggestions for the problem. :) Here's what I've tried: <script> function getImage1( ...

What is the best way to convert a recordset to an array using React?

I'm attempting to create an array by retrieving data from a SQL recordset: +------------+------------+------------+ | start_type | field_name | start_text | +------------+------------+------------+ | 0 | Field1 | some text. | +----------- ...

Issue with jQuery AJAX request not working as expected

I'm currently utilizing Rapid API to store my users' emails and passwords. Upon clicking, my send function should trigger, however, it seems that the program is not progressing through the AJAX call. I'm at a loss on how to proceed. Any ass ...

Retrieve the current URL of an IFRAME

How can I easily retrieve the current URL from an embedded iframe? The user will be navigating through various web pages. I assume that some JavaScript code would be needed for this task. ...