What is the best way to retrieve a linked filter in Vue from another?

I have created a file to store filters linked to my Vue object, and it is being imported into my App.js. One of the filters I have needs to use another filter:

Vue.filter('formatDateTime', value => {
    if (value)  return moment(String(value)).format('DD-MMM-YY hh:mm')
});
Vue.filter('getActivity', value =>
    (!value.lastvisited)
        ? 'Not visited yet' 
        : 'Last logged in ' + Vue.$options.filters.formatDateTime(value.lastvisited)
)

Unfortunately, this filter cannot reference the global Vue object. Is there a way to work around this issue? While I could simply duplicate the date formatting logic, I would prefer not to.

Answer №1

Another approach is to separate the definition and global registration.

This method also allows for usability and importability in non-Vue contexts.

// For example, in filters.js
export const formatDateTime = value => value 
  ? moment(String(value)).format('DD-MMM-YY hh:mm') 
  : null

export const getActivity = value => !value.lastvisited
  ? 'Not visited yet' 
  : 'Last logged in ' + formatDateTime(value.lastvisited)

// Then, in a filter-global-registration.js file
import { getActivity, formatDateTime } from 'filters.js'

Vue.filter('formatDateTime', formatDateTime);
Vue.filter('getActivity', getActivity)

Answer №2

One approach I often take is to establish a global reference to the main Vue object like this:

// Create a filter that invokes another filter.
Vue.filter('myFilter', () => {
    window.Vue.$options.filters.myOtherFilter(...);
});

// Initialize the main Vue object.
window.Vue = new Vue({

});

By doing this, you can access your filters with

window.Vue.$options.filters.myOtherFilter()
within your filter functions.

While it may not be the most ideal solution, I've found it useful in situations where you need to define plugins, services, or components without direct access to the current Vue instance.

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

Using HTML and CSS to create interactive icons that change color when clicked, similar to how a link behaves

Have you ever wondered if there's a way to make an icon act like a link when clicked, just like regular text links turning purple? And not just the last one clicked, but every single icon that gets clicked. Trying to use the :visited pseudo was unsucc ...

What is the best way to set up Flow type checking for functions passed as props in a React and Redux application?

In my app, I've been passing Redux action creators as props and want to improve type checking. Using the generic Function type has limitations, so I tried using the existential operator (*) in my Props type with no success in getting Flow to infer the ...

Unusual compilation issue encountered in Vue when trying to use a template for a slot

I encountered a strange issue where my Vue compiler was refusing to render the default named slot of a child component. Error: Codegen node is missing for element/if/for node. Apply appropriate transforms first. Even my VSCode highlighted this problem a ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

Upon successful authorization, the Node Express server will pass the access token to the React client app via OAuth in the callback

I am currently working on a node server that authenticates with a third party using oauth, similar to how Stack Overflow does. After authorizing the request and obtaining the access token and other essential information from the third party, my goal is to ...

Utilizing jQuery's then() method to display HTML and JSON outputs from printing operations

Currently, I am in the process of mastering jquery deferreds. When working with html on jsfiddle, I receive an object that contains two lines when printed within the then() statement: "success" and the html returned by the ajax request. For instance, upo ...

Every time I attempt to log into my app, I encounter a persistent 401 error message

I've implemented a user/login route that retrieves a user, compares their password with a hashed version, creates a token, and sends it to the front end. However, I encountered a persistent 401 error in the console on the front end, leading to the fin ...

Is it feasible for a form button to perform multiple actions simultaneously?

I am interested in exploring the possibility of having a submit form button perform multiple actions. Currently, I have a custom form that is sent to a Google Spreadsheet using AJAX and I am also utilizing the Blueimp Jquery File Upload plugin. My goal is ...

Arranging Material UI tabs on both sides

I'm currently working with Material UI tabs and I'm trying to achieve a layout where some tabs are positioned to the left and others to the right. For instance, if I have 5 tabs, I want 3 on the left and 2 on the right. I've tried placing th ...

Creating a variety of Flexslider slideshows on the fly

Check out this snippet of code: <?php foreach ($objVideos as $objVideo) : ?> jQuery('#carousel-<?php echo $objVideo->id; ?>').flexslider({ animation: "slide", controlNav: false, animationLoop: false, ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

What causes variables and functions to behave differently when it comes to hoisting?

I've recently been delving into some documentation and have noticed some inconsistencies in hoisting patterns within JavaScript. Consider the following examples: When it comes to functions, function abc(){ console.log("worked") } abc(); OUTPUT : ...

React.js encountered an error: Objects cannot be used as a React child (found: object containing keys {type, data})

My current project involves displaying MySQL data in a table using Node.js and React.js. However, I keep encountering the following error: Error: Objects are not valid as a React child (found: object with keys {type, data}). If you meant to render a colle ...

Can you provide a brief explanation for this bubble sort JavaScript code?

Can someone please explain to me what the line j<len-i is doing in this bubble sort code? I believe removing -i from that line will still make the program work properly, var arr=[3,5,4,7,8,9,30,0,-1]; function bubble_Sort(arr){ var len = arr.length, ...

What is the best method for transferring properties to the parent component using Vue router?

I have a multi-step form that each step has a different header structure. The only variation in the header among the steps is the wording, which changes as you progress through the steps. I am looking for a way to achieve this using Vue Router: pa ...

Developing ES6 modules in C++ using Node.js

Here is a previous example showcasing how to create a Node.js addon in C++: https://nodejs.org/api/addons.html You can use node-gyp to build it into a common JS module, which works well with the 'require' function. However, when trying to impo ...

I have a task of extracting information from a live Google map and generating a static Google map using API V3

I am working on a project that involves allowing users to create maps using Google Maps and then save the image. My current workaround uses both the Google Maps API V3 and the Static Maps API. The user can interact with the dynamic Google map by scrolling ...

When incorporating "<" or ">" into a parameter value in Angular Translate and then showcasing it in a textarea with ng-model

In my Angular Translate string, I am using a parameter that can be in the form of <test>. However, when this translate is displayed in a textarea, it shows up as &lt;test&gt; instead of <test>. Is there a way to ensure it appears correc ...

Proper method for incorporating a single database pool across an Express application

Disclaimer: This issue pertains to singleton objects in Node.js and not DB pools. While developing an Express.js application with the mysqljs node module for DB connections, I am interested in creating a single pool object that can be reused across differ ...

Cascading MVC 2 Dropdown menus

I am trying to bind a dropdown based on the change of another dropdown, but I keep getting an "Undefined" error. Here is my code snippet: <select id="BreakOutValue" class="input1_drop" onchange="onChange()" ></select> <%:Html.DropDownList( ...