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

Error in TypeScript when utilizing generic callbacks for varying event types

I'm currently working on developing a generic event handler that allows me to specify the event key, such as "pointermove", and have typescript automatically infer the event type, in this case PointerEvent. However, I am encountering an error when try ...

Exploring the dynamic loading of components within routes

Just starting out with Vue and experimenting with vue-router, I'm trying my hand at dynamically loading components without relying on additional libraries like webpack. So far, I've set up an index page and a router. Upon initial page load, I not ...

What is the best way to retrieve an object from a POST request using Angular AJAX calls in a NODEJS environment?

When the button is clicked, a method will be called. The code for this is as follows: .controller('templeDetailsList', function ($scope, $http, $ionicModal) { $scope.starclick = function(){ var newFav = [{ ...

I'm trying to figure out how to upload a file in Vue 2 by clicking on the label and displaying the file name. Can

I've been working on some code but it's missing the logic I need. My goal is to enable file upload by clicking the label instead of using the input tag. This is the Apply.vue file. <div class="line"> <h6>Upload CV:</h6& ...

NextJS build problem causing all content to become static

As a newcomer to NextJS with prior experience in basic React apps, I recently attempted to deploy a CRUD NextJS app (utilizing prisma and mongoDB). Everything runs smoothly with npm run dev, but issues arise when transitioning to npm run build followed by ...

Choosing an option in react-select causes the page to unexpectedly shift

Encountering a problem with a mobile modal developed using react-select. The selectors are within a div with fixed height and overflow-y: scroll. Upon selecting an option for the 'Choose observer' select, the entire modal briefly jumps down in th ...

Error encountered: Vue.js encountered an unexpected token, which is 'export'

Having an issue with Google location autocomplete, specifically this error: SyntaxError Unexpected token 'export' Here is the link to the functional code: https://codesandbox.io/s/nifty-bardeen-5eock ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

Vue component prop values are not properly recognized by Typescript

Below is a Vue component I have created for a generic sidebar that can be used multiple times with different data: <template> <div> <h5>{{ title }}</h5> <div v-for="prop of data" :key="prop.id"> ...

Using default language in Next.js internationalization: a step-by-step guide

I've been immersing myself in the Nextjs internationalization documentation for the past two days. My goal is to have support for two languages: en, fa. I also want to be able to switch between them with URLs structured like this: https://example.com ...

What is the method for determining if parsing is necessary or unnecessary?

Let's talk JSON: var datat= {"Model": "Model A", "Datase": [ { "Id": "DatchikSveta11", "Group": 2, "State": "on", "Dat ...

Steps for implementing a JavaScript script to modify all values within a table

I am facing an issue where I need certain "td" elements to disappear when the date associated with them has passed. However, currently only the first column is affected while others remain untouched. <script type="text/javascript"> //<![CDAT ...

Vue2 Component not displaying changes in data updates

I'm facing an issue where a Vue 2 component fails to render upon updating its data: Vue.component('image-slider', { data: function() { return { name : "Image1", src : "https://via.placeholder.com/250" } }, ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

Express router fails to mount

Struggling with my first project using expressjs, I have encountered an issue with a router not properly mounting. My approach involves the app mounting a router object which should then mount a second router object. While the first embedded router mounts ...

The radio button that disables other inputs only functions correctly for a single element when using Query Selector, but does not work with Query

I have attempted to develop a form section that is disabled when the user selects option A and enabled when they choose option B. document.getElementById('delivery').onclick = function() { var disabled = document.querySelectorAll(".dis ...

Is it possible to recognize when the mouse button is held down and the cursor is outside the viewport by using mouseleave detection?

Is there a way to detect when a user moves the mouse outside of the view-port, even if they are holding down the mouse button (for example, if the mouse is on the browser address bar)? In the code below, I am currently using mouseout and mouseleave to det ...

Exploring the Differences: innerHTML versus appendChild for Loading Scripts

Struggling to dynamically load scripts onto the DOM? function addScript(fileName) { document.body.innerHTML += `<script src='components/${fileName}/${fileName}.js'></script>` } addScript('message-interface') I prefer th ...

Updating the default date format input fields for React-bootstrap-daterangepicker in the United States

Hey there, I'm a newcomer to the world of React and Javascript and I've encountered an issue that has me stumped. I'm trying to change the default US dateformat in my React-bootstrap-daterangepicker, but I'm struggling to figure out how ...