A collection of handy unit conversion filters for use in Vue 2
vue-units
A plugin for adding handy conversion filters to your Vue.js project. Based on the convert-units package made by @ben-ng.
Installation
Install vue-units with NPM from the vue-units NPM repository by running the following command:
npm install vue-units --save
If you prefer to use Yarn, you can install it with the following command instead:
yarn add vue-units
Add it to your vue instance:
import Vue from 'vue';
import VueUnits from 'vue-units';
Vue.use(VueUnits)
If you don't use ES6, you can also include it as a script locally:
<script src="https://unpkg.com/vue-units@^1.0/vue-units.js"></script>
Usage
Filters
unit()
The filter unit(from, to, includeUnit)
is added to your Vue instance, which makes it easy to convert between a set of units in your templates:
<template>
<div id="app">
<p>{{1500 | unit('m', 'km', true)}}</p>
</div>
</template>
The above code will result in the following output:
1.5 km
If includeUnit
is false, only the converted value will be returned:
1.5
To see a list of available conversion units, please refer to the official repository for convert-units.
Prototype
You can access the instance of convert-units anywhere in your Vue templates, which gives you access to the additional functions that the convert-units package provides:
this.$units(12000).from('mm').to('m');
// 12 Metres
this.$units(12000).from('mm').toBest();
// 12 Meters (the smallest unit with a value above 1)
this.$units(12000).from('mm').toBest({ exclude: ['m'] })
// 1200 Centimeters (the smallest unit excluding meters)
this.$units(12000).from('mm').toBest({ cutOffNumber: 10 });
// 900 Centimeters (the smallest unit with a value equal to or above 10)
this.$units(12000)from('mm').toBest({ cutOffNumber: 10 })
// 10 Meters (the smallest unit with a value equal to or above 10)
this.$units(12000).from('m').possibilities();
// ["mm", "cm", "m", "km", "in", "yd", "ft-us", "ft", "mi"]
this.$units().measures();
// [ 'length', 'mass', 'volume' ]
For additional methods, please refer to the official repository for convert-units.
Example:
<script>
export default {
props: {
distance: {
type: Number,
default: 123456789
}
},
computed: {
shortDistance() {
const obj = this.$units(this.distance).from('cm2').toBest({
exclude: ['m2']
});
return `${obj.val} ${obj.unit}`;
}
}
}
</script>