Last active
November 22, 2021 00:42
-
-
Save ndabAP/d7a338407bb22794418bc64875af14ee to your computer and use it in GitHub Desktop.
Vue.js pluralize filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<p>I got {{ amount }} {{ 'cookie' | pluralize(amount) }}</p> | |
<button @click="decrement">Decrement</button> | |
</div> | |
</template> | |
<script> | |
export default { | |
data: () => ({ | |
amount: 5 | |
}), | |
methods: { | |
decrement () { | |
this.amount-- | |
} | |
} | |
} | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue' | |
Vue.filter('pluralize', (word, amount) => (amount > 1 || amount === 0) ? `${word}s` : word) | |
new Vue({render: create => create(App)}).$mount('#app') |
@iSWORD to make it even simpler to use:
Vue.filter('pluralize', (amount, singular, plural = null) => {
if (plural === null) {
plural = `${singular}s`;
}
return (amount > 1 || amount === 0) ? plural : singular;
});
Then if the word pluralizes "normally" you can just exclude the third argument:
// NOTE: Not how you actually use this, just using it as a normal function for example purposes
pluralize(1, 'cookie'); // => cookie
pluralize(2, 'cookie'); // => cookies
pluralize(1, 'octopus', 'octopi'); // => octopus
pluralize(2, 'octopus', 'octopi'); // => octopi
And while we're at it...
Vue.filter('pluralize', (amount, singular, plural = `${singular}s`) => amount === 1 ? singular : plural);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I decided to do it the more manual way with:
so that I can use it like this:
This is not very different from going completely manual but still saves a few strokes and ensures proper pluralization without adding more packages.