Vue.js methods bound as properties on a parent object

There are times when I come across scenarios where it would be convenient to bind methods as an object property rather than a direct Vue method. For instance, instead of:

<MyInput 
  :formatter="currencyFormat" 
  :parser="currencyParser" 
/>

It would be beneficial to have the ability to do something like this:

<MyInput 
  :formatter="formatter.currency.format"
  :parser="formatter.currency.parser" 
/>

This way, only formatter from the Vue class needs to be exposed without having to create separate wrapper methods for each binding case. It can eliminate unnecessary boilerplate code.

Is it feasible to achieve this? If so, what would the class implementation look like? I personally feel uneasy about placing an object with methods in data.

Answer №1

Due to the limited information available, I will be making a number of assumptions in my response.

TLDR

To achieve the desired functionality, you can have the method return an object and then execute it in your template, or utilize a computed property that returns an object.

Example (props are functions)

An example implementation could resemble the following (based on the assumptions made):

<script>
export default {
  /* other options */
  methods: {
    /* other methods */
    formatter() {
      const format = (value) => new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(value);
      const parser = (value) => parseFloat(value);

      return {
        currency: {
          format,
          parser,
        },
      };
    }
  },
}
</script>

Using the above method, you can implement the following in your template:

<MyInput 
  :formatter="formatter().currency.format"
  :parser="formatter().currency.parser" 
/>

The props formatter and parser will each be assigned two functions as defined within the returned Object.

Less boilerplate

To further reduce redundancy, consider the following approach:

<script>
export default {
  /* other options */
  methods: {
    /* other methods */
    formatter() {
      const formatter = (value) => new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(value); // matching the prop name 'formatter'
      const parser = (value) => parseFloat(value);

      return {
        currency: {
          formatter, // matching the prop name 'formatter'
          parser,
        },
      };
    }
  },
}
</script>

In your template:

<MyInput v-bind="formatter().currency" />

This will bind formatter.currency.formatter to the prop formatter, and similarly bind formatter.currency.parser to the prop parser.

Value is in parent component

If the props in MyInput need to be values instead of functions, and the value requiring parsing/formatting is stored within the data option of the parent component:

<script>
export default {
  /* other options */
  data() {
    return { 
      /* other data */
      myNumberValue: '9001' // It's actually over 9000
    } 
  },
  methods: {
    /* other methods */
    formatter() {
      const value = this.myNumberValue;
      const formatter = new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR', }).format(value);
      const parser = parseFloat(value);

      return {
        currency: {
          formatter,
          parser,
        },
      };
    },
  },
};
</script>

Does this provide a satisfactory answer to your question?

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

Challenges arising from the usage of Vue component state in TypeScript

I'm encountering an issue with a basic Vue component. I'm attempting to trigger a rerender of v-if="isTouched" by setting the setter (via the touch event). Vue dev tools indicate that the _isTouched variable is showing as "undefined". My underst ...

Prevent automatic scrolling to the top following an AJAX request

Question about Preventing Scrolling to Top: How can I prevent a web page from scrolling to the top when a link triggers javascript? Whenever an ajax request occurs, my browser automatically scrolls to the top. In order to return to my desired div sect ...

What is the method for retrieving a computed state variable?

In Vue Class Component, accessing the value of a computed variable can be a bit tricky. If you try to access it using this.bar, you may encounter an error like this: Property 'bar' does not exist on type 'Vue'. <script lang="ts& ...

DNN Unveils New "Exit Confirmation" Pop-up Feature When Clicking External Links

Greetings fellow beginners! I've been struggling to make some changes on our DNN site (Evoq 8.5) with no success so far. The issue at hand is that we have links throughout our entire website that follow this format: <a href="www.site.com" class="e ...

button that decreases in size when clicked on

Currently, I am dealing with an element that functions as a button using a combination of Javascript and CSS. To better illustrate the issue, I will simplify the example by removing unnecessary details. The main problem lies in the fact that when this elem ...

Display an HTML tag with JavaScript

My code is in both HTML and TS files. The content stored in the Description variable looks like this: <div>aaaa</div><div>bbbb</div><div>cccc</div> Currently, the output displays as follows: aaaabbbbcccc I want to modi ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

How to Implement Click Actions on Elements in AngularJS

Just starting out with angularjs and I have a scenario with jQuery. handleClick(); function handleClick() { var doubleClick = false; $('#text span.word').on('click', function() { var that = this; setTimeout(funct ...

Why is req.user returning as undefined when using Express and Passport?

After setting up my app to redirect to "/", I encountered an issue where req.user is undefined. However, in the twitter callback, req.user provides me with the necessary data. It seems that I lose the data on the redirection. Even though there is ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

search engine optimized for easy input via keyboard

I have successfully incorporated AJAX search functionality into my project, inspired by this example here. The unique feature of this implementation is the ability to navigate through search results using the TAB key. The structure of my search results tab ...

Using Vuejs to customize the color of disabled drop-down text

I'm trying to achieve the functionality where selecting an item from a dropdown list disables that option. Currently, my code works as expected, but I find the color of the disabled text too light. Is there a way to adjust the color of the disabled te ...

Navigating through an array of functions, some of which may return promises while others do not

Is there a way to efficiently iterate and execute an array of functions where some return promises, requiring the use of await, while most do not return promises, necessitating them to be set as async? for (let i = 0; i < this.steps.length; i++) { ...

Kik Card - Using Synchronous XMLHttpRequest within the Kik.js Script

Getting ready to create a mobile web app powered by Kik! First step, insert the Kik.js script at the bottom of your HTML page... <!-- add this script to your webpage --> <script src="http://cdn.kik.com/kik/2.3.6/kik.js"></script> Excel ...

My function seems to be functioning perfectly fine in Angular and Express, but for some reason, it's not working in Parse Cloud Code. What could

I am facing an issue with my code where it seems to be stuck. After testing it in both Angular and Express, I realized that the code is only progressing up to a certain point due to the requirement of the Master Key to edit the User table with new data. ...

Performing a Jquery Ajax get request on multiple URLs within a single function

In my current setup, I have a form with a select dropdown and three submit buttons labeled as "Daily new likes", "Daily unlikes" and "Daily page views". The form includes an Ajax call within the submitForm function that sends the selected option value to a ...

What are some alternative solutions when functional component props, state, or store are not being updated within a function?

Initially, I need to outline the goal. In React frontend, I display data that aligns with database rows and allow users to perform CRUD operations on them. However, in addition to actual database rows, I include dummy rows in the JSON sent to the frontend ...

AngularJS Element Connections

I have the following component: (function () { "use strict"; angular.module("application_module") .component('tab', { controller: 'TabCtrl', templateUrl: 'app/component/application/app-heade ...

Creating a Form with a Custom Format in AngularJS

Just starting out with AngularJS and currently working with ACTIVITI. I'm looking to create a form in a specific structure where each response follows this format: { "taskId" : "5", "properties" : [ { "id" : "room", ...