Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a utility class and using it within a vue component

A vue application I am working on currently has lots of code redundancies relating to date functions. In an effort to reduce these redundancies, I'd like to create a utility class as shown below, import it and set it to a Vue data property within the component, so I can call the date functions within it.

I am not certain on the best way to implement this. The current implementation results in an error saying TypeError: this.dates is undefined and my goal is not only to resolve this error but create/utilize the class in the Vue environment using best standards.

Importing utility class

    import Dates from "./utility/Dates";
...

Component

const contactEditView = Vue.component('contact-edit-view', {
        data() {
            return {
                contact: this.myContact
                dates: Dates
            }
        },
...

Dates.js

export default {
    dateSmall(date) {
        return moment(date).format('L'); 
    },
    dateMedium(date) {
        return moment(date).format('lll');
    },
    dateLarge(date) {
        return moment(date).format('LLL');
    }
};

View

Date of Birth: {{ dates.dateMedium(contact.dob) }}
like image 712
AnchovyLegend Avatar asked Jan 24 '18 14:01

AnchovyLegend


People also ask

How do I add a class to my Vue component?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component. Of course, there is a lot more we can do here with dynamic classes in Vue.

How do I add styles to VueJS?

In Vue. js, we can add an inline style to our element by binding the style attribute in the HTML tag. For reference, :style is shorthand for v-bind:style . Inline styling can be done in two ways: using object syntax or array syntax.

How do I transfer data from components to Vue?

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!


Video Answer


2 Answers

My suggestion for this is to use a plugin option in Vue. About Vue plugin

So you will crate a new folder called services, add file yourCustomDateFormater.js:

const dateFormater = {}

dateFormater.install = function (Vue, options) {

   Vue.prototype.$dateSmall = (value) => {
     return moment(date).format('L')
   }
   
   Vue.prototype.$dateMedium = (value) => {
     return moment(date).format('lll')
   }
}

In main.js:

import YourCustomDateFormater from './services/yourCustomDateFormater'

Vue.use(YourCustomDateFormater)

And you can use it anywhere, like this:

this.$dateSmall(yourValue)

Or, if you want to use mixin. Read more about mixin

Create a new file dateFormater.js

export default {
  methods: {
    callMethod () {
      console.log('my method')
    }
  }
}

Your component:

import dateFormater from '../services/dateFormater'

  export default {
    mixins: [dateFormater],
    mounted () {
      this.callMethod() // Call your function
    }
  }

Note: "Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components. In most cases, you should only use it for custom option handling like demonstrated in the example above. It’s also a good idea to ship them as Plugins to avoid duplicate application." - Vue documentation

like image 155
latovic Avatar answered Nov 12 '22 02:11

latovic


dateUtilsjs

import moment from 'moment-timezone'

function formatDateTime(date) {
    return moment.utc(date).format("M/D/yyyy h:mm A")
}

export { formatDateTime }

Component JS

...
import { formatDateTime } from '../utils/dateUtils'
...
methods: {
    formatDateTime,
}

Used within component

{{ formatDateTime(date) }}
like image 32
Half_Duplex Avatar answered Nov 12 '22 03:11

Half_Duplex