Giter Club home page Giter Club logo

vue2-filters's Introduction

vue2-filters Build Status

A collection Vue.js filters.

Installation

Direct include

Simply include vue2-filters after Vue and it will install itself automatically:

<script src="vue.js"></script>
<script src="vue2-filters.min.js"></script>

To use one of the predefined methods (such as limitBy, filterBy, find, or orderBy) in your component, you also need to add Vue2Filters.mixin to mixin list:

<script>
  new Vue({
    ...
    mixins: [Vue2Filters.mixin],
    ...
  })
</script>

CDN jsDelivr Hits

<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue2-filters/dist/vue2-filters.min.js"></script>

To use one of the predefined methods (such as limitBy, filterBy, find, or orderBy) in your component, you also need to add Vue2Filters.mixin to mixin list:

<script>
  new Vue({
    ...
    mixins: [Vue2Filters.mixin],
    ...
  })
</script>

NPM npm

npm install vue2-filters

When used with a module system, you must explicitly install the filters via Vue.use():

import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

You don't need to do this when using global script tags.

To use one of the predefined methods (such as limitBy, filterBy, find, or orderBy) in your component, you also need to add Vue2Filters.mixin to mixin list:

import Vue2Filters from 'vue2-filters'

export default {
  ...
  mixins: [Vue2Filters.mixin],
  ...
}

Nuxt.js

npm install vue2-filters

When create file plugins/vue2-filters.js:

import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

Then, add the file inside the plugins key of nuxt.config.js:

module.exports = {
  //...
  plugins: [
    '~/plugins/vue2-filters'
  ],
  //...
}

To use one of the predefined methods (such as limitBy, filterBy, find, or orderBy) in your component, you also need to add Vue2Filters.mixin to mixin list:

import Vue2Filters from 'vue2-filters'

export default {
  ...
  mixins: [Vue2Filters.mixin],
  ...
}

Available Filters

Usage

capitalize

  • Arguments:

    • {Object} [options] - default: {}
  • Options:

    • {Boolean} [onlyFirstLetter] - default: false
  • Example:

    {{ msg | capitalize }} // 'abc' => 'Abc'

    Capitalize only first letter of sentence:

    {{ msg | capitalize({ onlyFirstLetter: true }) }} // 'lorem ipsum dolor' => 'Lorem ipsum dolor'

uppercase

  • Example:

    {{ msg | uppercase }} // 'abc' => 'ABC'

lowercase

  • Example:

    {{ msg | lowercase }} // 'ABC' => 'abc'

placeholder

  • Arguments:

    • {String} [placeholder]
  • Example:

    {{ msg | placeholder('Text if msg is missing') }} // '' => 'Text if msg is missing'

truncate

  • Arguments:

    • {Number} [length] - default: 15
  • Example:

    {{ msg | truncate(10) }} // 'lorem ipsum dolor' => 'lorem ipsu...'

repeat

  • Arguments:

    • {Number} [amount] - default: 1
  • Example:

    {{ msg | repeat(3) }} // 'a' => 'aaa'

reverse

  • Example:

    {{ msg | reverse }} // 'abc' => 'cba'

wrap

  • Arguments:

    • {String} [string]
  • Example:

    {{ msg | wrap('###') }} // 'ipsum' => '###ipsum###'

number

  • Arguments:

    • {String} [format] - default: ''
    • {Object} [options] - default: {}
  • Options:

    • {String} [thousandsSeparator] - default: ','
    • {String} [decimalSeparator] - default: '.'
  • Examples:

    {{ 123456 | number('0,0') }} // => 123,456

    Change the number of digits after the decimal point:

    {{ 12345.67 | number('0.0000') }} // => 12345.6700

    Add a plus or minus sign to the beginning:

    {{ 123456 | number('+0') }} // => +123456
    {{ 123456 | number('-0') }} // => -123456

    Show number in thousand (K) or in millions (M):

    {{ 123456 | number('0a') }} // => 123K
    {{ 123456 | number('0 a') }} // => 123 K
    {{ 123456789 | number('0a') }} // => 123M

    Use a different thousands separator:

    {{ 1234567 | number('0,0', { thousandsSeparator: ' ' }) }} // => 1 234 567

    Use a different decimal separator:

    {{ 12345.67 | number('0.00', { decimalSeparator: '|' }) }} // => 12,345|67

bytes

  • Arguments:

    • {Number} [decimalDigits] - default: 2
  • Examples:

    {{ 1 | bytes }}              // => 1 byte
    {{ 20 | bytes }}             // => 20 bytes
    {{ 2000 | bytes }}           // => 1.95 kB
    {{ 2000000 | bytes }}        // => 1.91 MB
    {{ 2000000000 | bytes }}     // => 1.86 GB
    {{ 2000000000000 | bytes }}  // => 1.82 TB

    Change the number of digits after the decimal point:

    {{ 2000000000 | bytes(4) }}  // => 1.8626 GB

percent

  • Arguments:

    • {Number} [decimalDigits] - default: 0
    • {Number} [multiplier] - default: 100
    • {Object} [options] - default: {}
  • Options:

    • {String} [decimalSeparator] - default: '.'
  • Examples:

    {{ 0.01 | percent }} // => 1%
    {{ 0.1 | percent }} // => 10%
    {{ 1 | percent }} // => 100%
    {{ 100 | percent }} // => 10000%
    {{ 0.97 | percent }} // => 97%

    Change the number of digits after the decimal point:

    {{ 0.974878234 | percent(3) }} // => 97.488%

    Change the multiplier:

    {{ 0.974878234 | percent(3, 150) }} // => 146.232%

    Use a different decimal separator:

    {{ 0.07 | percent(2, 100, { decimalSeparator: '|' }) }} // => 7|00%

currency

  • Arguments:

    • {String} [symbol] - default: '$'
    • {Number} [decimalDigits] - default: 2
    • {Object} [options] - default: {}
  • Options:

    • {String} [thousandsSeparator] - default: ','
    • {String} [decimalSeparator] - default: '.'
    • {Boolean} [symbolOnLeft] - default: true
    • {Boolean} [spaceBetweenAmountAndSymbol] - default: false
    • {Boolean} [showPlusSign] - default: false
  • Example:

    {{ amount | currency }} // 12345 => $12,345.00

    Use a different symbol:

    {{ amount | currency('£') }} // 12345 => £12,345.00

    Use a different number decimal places:

    {{ amount | currency('₽', 0) }} // 12345 => ₽12,345

    Use a different thousands separator:

    {{ amount | currency('$', 0, { thousandsSeparator: '.' }) }} // 12345 => $12.345

    Use a different decimal separator:

    {{ amount | currency('$', 2, { decimalSeparator: ',' }) }} // 12345 => $12,345,00

    Use symbol on right:

    {{ amount | currency('$', 0, { symbolOnLeft: false }) }} // 12345 => 12,345$

    Add space between amount and symbol:

    {{ amount | currency('$', 0, { spaceBetweenAmountAndSymbol: true }) }} // 12345 => $ 12,345

    Show the plus sign if the value is greater than zero:

    {{ amount | currency('$', 0, { showPlusSign: true }) }} // 12345 => +$12,345

    Use multiple options:

    {{ amount | currency('kr', 2, { symbolOnLeft: false, spaceBetweenAmountAndSymbol: true }) }} // 12345 => 12,345.00 kr

pluralize

  • Arguments:

    • {String|Array} single or Array(single, double, triple, ...)
    • {Object} [options] - default: {}
  • Options:

    • {Boolean} [includeNumber] - default: false
  • Example:

    {{ count }} {{ count | pluralize('item') }} 
    
    // 1 => '1 item'
    // 2 => '2 items'

    Use an array of words:

    {{ count }} {{ count | pluralize(['fry', 'fries']) }} 
    
    // 1 => '1 fry'
    // 2 => '2 fries'
    // 3 => '3 fries'

    Include number to output:

    {{ count | pluralize('test', { includeNumber: true }) }} 
    
    // 1 => '1 test'
    // 2 => '2 tests'

ordinal

  • Arguments:

    • {Object} [options] - default: {}
  • Options:

    • {Boolean} [includeNumber] - default: false
  • Example:

    {{ date | ordinal }} 
    
    // 1 => 'st'
    // 2 => 'nd'
    // 3 => 'rd'
    // 4 => 'th'
    // 5 => 'th'

    Include number to output:

    {{ date | ordinal({ includeNumber: true }) }} 
    
    // 1 => '1st'
    // 2 => '2nd'

limitBy

  • Arguments:

    • {Number|Array} [items]
    • {Number} [limit]
    • {Number} [offset]
  • Example:

    <!-- only display first 10 items -->
    <div v-for="item in limitBy(items, 10)">{{ item }}</div>
    <!-- display items 5 to 15 -->
    <div v-for="item in limitBy(items, 10, 5)">{{ item }}</div>
    <!-- with a Range -->
    <div v-for="n in limitBy(10, 4, 2)">{{ n }}</div>

filterBy

  • Arguments:

    • {Array} [items]
    • {String} [query]
    • {String} [searchKey]
  • Example:

    <!-- only items that contain the target string "hello" will be displayed -->
    <div v-for="item in filterBy(items, 'hello')">
    <!-- the filter will only search for "Jack" in the name field of each user object -->
    <div v-for="user in filterBy(users, 'Jack', 'name')">
    <!-- the filter will only search for "Bonnie" in the name or age fields of each user object -->
    <div v-for="user in filterBy(users, 'Bonnie', 'name', 'age')">
    <!-- filter using a custom function -->
    <div v-for="user in filterBy(users, user => user.age > 16 && user.age < 60)">

find

  • Arguments:

    • {Array} [items]
    • {String} [query]
    • {String} [searchKey]
  • Example:

    <!-- only the first item that contains the target string "hello" will be displayed -->
    <div v-for="item in find(items, 'hello')">
    <!-- the filter will only search for "Bonnie" in the name or age fields of each user object and return the first result -->
    <div v-for="user in find(users, 'Bonnie', 'name', 'age')">

orderBy

  • Arguments:

    • {Array} [items]
    • {String} [sortKey]
    • {Number} [order] - default: 1
  • Example:

    Sort users by name:

    <ul>
      <li v-for="user in orderBy(users, 'name')">
        {{ user.name }}
      </li>
    </ul>

    In descending order:

    <ul>
      <li v-for="user in orderBy(users, 'name', -1)">
        {{ user.name }}
      </li>
    </ul>

    Sort primitive values:

    <ul>
      <li v-for="name in orderBy(names, true)">
        {{ name }}
      </li>
    </ul>

Global Configuration

If you need to override filter options globally you can do so by passing an object into Vue.use() function as the second argument:

import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

var Vue2FiltersConfig = {
  capitalize: {
    onlyFirstLetter: false
  },
  number: {
    format: '0',
    thousandsSeparator: ',',
    decimalSeparator: '.'
  },
  bytes: {
    decimalDigits: 2
  },
  percent: {
    decimalDigits: 2,
    multiplier: 100,
    decimalSeparator: '.'
  },
  currency: {
    symbol: '$',
    decimalDigits: 2,
    thousandsSeparator: ',',
    decimalSeparator: '.',
    symbolOnLeft: true,
    spaceBetweenAmountAndSymbol: false,
    showPlusSign: false
  },
  pluralize: {
    includeNumber: false
  },
  ordinal: {
    includeNumber: false
  }
}

Vue.use(Vue2Filters, Vue2FiltersConfig)

Programmatic Usage

Aside from using filters inside templates you can do this programmatically using default filters object:

this.$options.filters.filterName(value)

For example, here's how you can use the currencyfilter:

this.$options.filters.currency(100) // => $100.00

As for such filters as limitBy, filterBy, find, or orderBy, they can be used as usual methods:

this.limitBy([1,2,3,4,5], 2) // => [1,2]

Upgrade Guide

Upgrade to 0.6.0 from 0.5.*

The pluralize filter

The pluralize filter arguments order has been changed. In the new version to specify several variants of words you can do this by passing an array as first argument, like so:

{{ count | pluralize(['item', 'items']) }}

In addition, the function of translate a regular number to its ordinal representation was removed from the pluralize filter. Now there is a separate ordinal filter for this:

{{ count | ordinal }}

Upgrade to 0.5.0 from 0.4.*

The capitalize filter

To match the definition of the word "capitalize", the default filter behavior has been changed. The filter now capitalizes the first letter in each word in the sentence (like CSS property text-transform).

If you want capitalize only first letter of sentence, you just need to add the onlyFirstLetter parameter to the filter, like so:

{{ msg | capitalize({ onlyFirstLetter: true }) }}

Upgrade to 0.4.0 from 0.3.*

In the new version it was decided to refuse from global registration of mixins, as it could lead to errors when using this package with other packages. Therefore, you need to manually add Vue2Filters.mixin into the mixin list of your components if you use at least one of the predefined methods (such as limitBy, filterBy, find or orderBy):

export default {
  ...
  mixins: [Vue2Filters.mixin],
  ...
}

You can read more about the reasons for this change here

Contribution

If you find a bug or want to contribute to the code or documentation, you can help by submitting an issue or a pull request.

License

MIT

vue2-filters's People

Contributors

bastiaanjansen avatar chriys avatar ctf0 avatar enricosottile avatar freearhey avatar garhbod avatar lukasdrgon avatar marcelodolza avatar marcushultman avatar ospencer avatar rezaeimehr avatar shershen08 avatar tsulli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue2-filters's Issues

Unit testing examples

I am trying to write unit tests for a component that uses the pluralize filter, but I cannot seem to get it to work. I came here looking for some examples on how to import it as part of a test, but there seems to be no documentation on how to properly mock it out. If you could add some testing examples to your documentation, it would be greatly appreciated. Thanks

filterBy implementation

I think filterBy implementation is wrong. It searches a substring in a whole string instead of searching by first letters. For example, if I type "W" for ["Whatson", "Power", "Slower"] I must find Whatson only - not all of this words.

P. S. I've looked for Vue 1.0 implementation - it is the same, so... may be it's not bad. But still I think it's not what it must be. May be there must be another filter - searchBy, for example... Like google-search.

how to get the changed list made with orderBy ?

lets say we have a list of 10 items, now when we use orderBy the list order will change but as the filter use a cloned list its not possible to make any operations on the original list as the index will be wrong.

so is there a way i could get that cloned list made by the filter ?
or better yet mutate the original list instead ?
or if neither is good, maybe the filter could fire an event with the new list then i can use it to make operations without mutating the original list ?

Feature: Allow custom filters

Will be great if you allow to create my own custom filters, for example i want to create one filter for format date with the moment library

Example:

{{ user.created_at | date: LTS }}
// calls moment(date).format('LTS');

use vuejs-filters instead?

Hi, just wanted to know if you want to use vuejs-filters handle on npm. I made it before knowing there was a repo in github. I am about to delete it from npm as I never actually made the library (at least a working one)

let me know if you need it, so I can delete it and you can take it. I think it makes more sense to use vuejs-filters in my opinion

Help me please ! urgent: I do not know how to do it

Hello,

Hello,
I would like on the action 'click' of a button executed action / filter "filberBy ()".

Do you have a complete example to provide me?

Here is a part of my code (but it does not work) :

<b-checkbox @input="filterBy(this.liste,'str_search','lib_name')"  v-model="search" >esrs</b-checkbox> 
<article  v-for="item in filterBy(this.liste)" :key="item.id"  :id="item.lib">
...
</article>

Thank you.

in method?

how use currency in method vue?
row.push(item.price);

CSP eval() error

vue2-filters doesn't work with a secure/strong CSP.
Currently, vue2-filters only works if you add the unsafe-eval CSP directive. Bad practice and unsafe!

I have to use version 0.3.0 because multiple eval()'s are used in newer versions.

Example:

"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _util_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/index */ \"./src/util/index.js\");\n\n/**\n * Filter filter for arrays\n *\n * @param {Array} arr\n * @param {String} prop\n * @param {String|Number} search\n */\n\nfunction filterBy(arr, search) {\n var arr = _util_index__WEBPACK_IMPORTED_MODULE_0__[\"default\"].convertArray(arr);\n\n if (search == null) {\n return arr;\n }\n\n if (typeof search === 'function') {\n return arr.filter(search);\n } // cast to lowercase string\n\n\n search = ('' + search).toLowerCase();\n var n = 2; // extract and flatten keys\n\n var keys = Array.prototype.concat.apply([], _util_index__WEBPACK_IMPORTED_MODULE_0__[\"default\"].toArray(arguments, n));\n var res = [];\n var item, key, val, j;\n\n for (var i = 0, l = arr.length; i < l; i++) {\n item = arr[i];\n val = item && item.$value || item;\n j = keys.length;\n\n if (j) {\n while (j--) {\n key = keys[j];\n\n if (key === '$key' && contains(item.$key, search) || contains(_util_index__WEBPACK_IMPORTED_MODULE_0__[\"default\"].getPath(val, key), search)) {\n res.push(item);\n break;\n }\n }\n } else if (contains(item, search)) {\n res.push(item);\n }\n }\n\n return res;\n}\n\nfunction contains(val, search) {\n var i;\n\n if (_util_index__WEBPACK_IMPORTED_MODULE_0__[\"default\"].isPlainObject(val)) {\n var keys = Object.keys(val);\n i = keys.length;\n\n while (i--) {\n if (contains(val[keys[i]], search)) {\n return true;\n }\n }\n } else if (_util_index__WEBPACK_IMPORTED_MODULE_0__[\"default\"].isArray(val)) {\n i = val.length;\n\n while (i--) {\n if (contains(val[i], search)) {\n return true;\n }\n }\n } else if (val != null) {\n return val.toString().toLowerCase().indexOf(search) > -1;\n }\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (filterBy);\n\n//# sourceURL=webpack:///./src/array/filterBy.js?");

orderBy with multiple orders

Hi thanks and congratulations for your work =)
I have one doubt.
Sometimes i need order by name and age for example. How i can do this?
Have something like this? orderBy(users, ['name', 'age'], -1)

It's possible make this with the plugin in any other form?

Thanks again.

Method "filterBy" has already been defined as a prop.

Hello, i think there is some bug in using filterBy prop on the package... i am using it with vue-select and this error come out... is there any solution that the prop is not using that? so i can use it with vue-select?

how to use orderBy and filterBy together ?

hello,

i have following

buttons

      <button @click="ordby('likes')">Sort by likes</button>
      <button>all</button>      
      <button>image</button>
      <button>video</button>

and my code is following

<div v-for="(value, key) in orderBy(obj,this.ord,-1)">
        <p>Likes: {{value.likes}}</p>
        <p>Type: {{value.type}}</p>
</div> 

so at the moment i can do the order by depend on likes when i click on the sort by likes but how i can do the filter also
is it possible to add the filterBy also in the v-for along with orderBy ??

and I have 3 conditions where I need to show all or show image or video

thanks in advance

How to use Multiple filters in one loop ?

While working with a project i need to filter throw some of arguments like 'name', 'class', 'value' from one loop, so i used <div v-for="post in filterBy(projectlist, cityFilter, 'city' | localityFilter, 'city')" > , but it is not working, also i could't able to figure it out .

Currency filter is missing option to control sign position and dot/comma setting

Hi!
I checked the source for the currency filter and realized that there is no way to specify the position of the
currency sign or specify if delimiters should be dots or commas.

In some locales like Swedish the rules for currency presentation is different e.g.
given 123456789 | currency('kr')
The filter produces:
kr1,234,567.89
But according to Swedish standard the formatting should be:
1 234 567,89 kr

In other words, I'd like to submit a feature-request to be able to control the decimal-separator and the thousand-separator and of course placement of currency-sign.

Capitalize not capitalizing every word by default

As per the docs, the capitalize function should capitalize every separate word in the string. By default, our item.supplier is all capitals. I use the lowercase filter to lowercase everything, and use capitalize to capitalize the words.

So in short:
Initial string: "SOME STRING"
After lowercase: "some string"
After capitalize: "Some string"

I tried setting the prop onlyFirstLetter to false, but that doesn't work.

annotations.push({
  icon: 'briefcase',
  title: this.$options.filters.capitalize(
    this.$options.filters.lowercase(item.supplier),
  ),
});

IE11 Fix

I got an error in IE11 and fixed it by changing:

var Vue2Filters = {
install(Vue) {

to:

var Vue2Filters = {
install: function(Vue) {

Just wanted to let you know!

Issue while building

I am getting this error when I try to npm run build:

ERROR in build.js from UglifyJs Unexpected token: punc (() [./~/vue2-filters/dist/vue2-filters.js:294,0][build.js:50404,9]

Help =(

Suggestion to add a pluralize variant for quantity-label pairs

As in a quantity-unit string, eg. "discance of 10 km", the string "need 10 items" is a value-label pair, and it is very commom... Need only a simple return value + ' ' + pluralize(value), or

function pluralize_qt (value) {
  var args = util.toArray(arguments, 1)
  var label = args.length > 1
    ? (args[value % 10 - 1] || args[args.length - 1])
    : (args[0] + (value === 1 ? '' : 's'));
  return value + ' '+ label;
}

orderBy filter requires additional parameter to perform ordering

Heres the code that should work according to the documentation:
<li v-for="user in orderBy(users, 'name')">
but the sort will not work with this setup. But if we add another argument it will work:
<li v-for="user in orderBy(users, 'name', 'name')">

Same for the reverse sorting:
<li v-for="user in orderBy(users, 'name', -1)"> - doesnt work
<li v-for="user in orderBy(users, 'name', 'name', '-1')"> - works

I`ve checked the code for the orderBy filter. Seems the problem is in the way how the sortorder is retrieved and args array is adjusted after that and how the sortKey is retrieved after that. I can submit a pull request if needed.

v0.4.0 orderBy is not defined error

New release throwing this error on every instance.

ReferenceError: orderBy is not defined.

Error disappears when orderBy is replaced with Vue2Filters.mixin.methods.orderBy in template.

Error log is attached below:
v4.0.0_error.log

Defaults are not changeable

Like mentioned in #43, there is no way to change default values, these are hard coded. A possible workaround is to define your own filter.

Could you please define defaults which you can overwrite on demand?

Currency decimal

Hi,

Is it possible to get the currency euro-style, f.x. 1.000 instead of 1,000 ? I mean swapping the comma with a dot? :)

500 (Cannot read property 'slice' of undefined)

function limitBy (arr, n, offset) {
offset = offset ? parseInt(offset, 10) : 0
n = WEBPACK_IMPORTED_MODULE_0__util_index["a" /* default */].toNumber(n)
return typeof n === 'number'
? arr.slice(offset, offset + n)
: arr
}

error
500 (Cannot read property 'slice' of undefined)

How can I call filte from my nuxt.js component

I have installed the vue2-filters in nuxt like described in the docs. The filters are working in my component template like this {{ someVaue | capitalize }}.

How can I use these filters in my component inside methods? Something like this for example:

<script>
export default {
  methods: {
    someMethod () {
      this.value = someValue | capitalize
    },
  }
}
</script>

I have come up to that you can access your filters trough this.$options.filters. But in case of my component this.$options.filters returns and empty object {}?

Namespace methods (and maybe other filters)

The array filters are implemented as methods in a mixin, which can cause problems if the names collide with methods in other components or mixins. (I just spent a couple hours tracking down why a 3rd party component wasn't working, and turned out they had a prop named filterBy that was getting clobbered by the filterBy method from vue-filters.

The names used are pretty common, so this is likely to cause many issues when you mix in the filters globally (as you do in Nuxt with a plugin).

Probably the best solution would be to namespace all the methods so they are unlikely to collide. E.g. vfOrderBy instead of orderBy. This could be optional so those who don't need it (they're using filters locally in a component instead of globally in an app) wouldn't have to use it.

Calling orderBy programatically

This isn't an issue, more a question - I can use orderBy quite easily when using it on a v-for, but how do I run this programmatically in a method?

0.2.0 breaks uglifyjs

ERROR in static/js/vendor.ec67e09dea199da20c96.js from UglifyJs
Unexpected token: punc (() [./node_modules/vue2-filters/dist/vue2-filters.js:477,0][static/js/vendor.ec67e09dea199da20c96.js:49045,9]

Fix readme!

This repository's README.md is broken. :c

Blank spaces between query params

Hi @freearhey great plugin !. I have my models like this:
person: {"name": {"first": "Mark", "last": "Twain"}

Im using the filterBy method
person in filterBy (people, searchQuery, 'name.first', 'name.last')

It works great with single first name or last name, but when the searchQuery data model has a blank space for example: "Mark Twain" it wont return any result. So te exact match its not working. Couldnt find a workaround this. Maybe you can help me. Thanks

Can it works with SSR?

I tried to use this package in my SSR-based Vue project, but it not works:

   ReferenceError: window is not defined
    at Object.<anonymous> (/www/node_modules/vue2-filters/dist/vue2-filters.js:625:5)
    at __webpack_require__ (/www/node_modules/vue2-filters/dist/vue2-filters.js:30:30)
    at ArrayProto (/www/node_modules/vue2-filters/dist/vue2-filters.js:74:18)
    at /www/node_modules/vue2-filters/dist/vue2-filters.js:77:10
    at webpackUniversalModuleDefinition (/www/node_modules/vue2-filters/dist/vue2-filters.js:3:20)
    at Object.<anonymous> (/www/node_modules/vue2-filters/dist/vue2-filters.js:10:3)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at r (/www/node_modules/vue-server-renderer/build.js:5817:16)
    at Object.<anonymous> (__vue_ssr_bundle__:30158:18)
    at __webpack_require__ (__vue_ssr_bundle__:21:30)

Error here because there is "if (window.Vue)" in code but window is undefined when code executes on server.

Thanks.

Different currencies

Hello,

is there any way to use different kinds of currencies on the currency filter?
For instance, {{ data.result | currency | € }} to display the currency in euros?

Thank you

After installing is not working

Aftetr install the plugin using NPM and applying it using
Vue.use(Vue2Filters);

i receive this error
Failed to resolve filter: pluralize

(TS) Could not find a declaration file for module 'vue2-filters'. '/node_modules/vue2-filters/dist/vue2-filters.js' implicitly has an 'any' type. Try `npm install @types/vue2-filters` if it exists or add a new declaration (.d.ts) file containing `declare module 'vue2-filters'

I get this error when trying to use it in my Vue2 project along with Typescript on this line
import Vue2Filters from "vue2-filters";

(TS) Could not find a declaration file for module 'vue2-filters'. '/node_modules/vue2-filters/dist/vue2-filters.js' implicitly has an 'any' type. Try npm install @types/vue2-filters if it exists or add a new declaration (.d.ts) file containing `declare module 'vue2-filters

syntax error in IE11 when including via CDN

When including via CDN (https://cdn.jsdelivr.net/npm/vue2-filters/dist/vue2-filters.min.js or https://cdn.jsdelivr.net/npm/vue2-filters/dist/vue2-filters.js), IE11 is showing a syntax error at line 215, which is as follows:

eval("__webpack_require__.r(__webpack_exports__);\n/**\n * Converts a string into Capitalize\n * \n * 'abc' => 'Abc'\n * \n * @param {Object} options\n */\n\nfunction capitalize (value, options) {\n options = options || {}\n var onlyFirstLetter = options.onlyFirstLetter != null ? options.onlyFirstLetter : false\n if (!value && value !== 0) return ''\n if(onlyFirstLetter === true) {\n return value.charAt(0).toUpperCase() + value.slice(1)\n } else {\n value = value.toString().toLowerCase().split(' ')\n return value.map( item => {\n return item.charAt(0).toUpperCase() + item.slice(1)\n }).join(' ')\n }\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (capitalize);\n\n\n//# sourceURL=webpack:///./src/string/capitalize.js?");

Thoughts on what the issue might be?

Thanks in advance!

Can't run with webpack

Install as it pointed in docs.

Got

Uncaught TypeError: plugin.apply is not a function

How change default options?

It's possible change the default options to a filter? Like Router Construction Options

Example:

import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

declare type Vue2FiltersConfig = {
  currency: {
        'R$ ',
        { thousandsSeparator: '.', decimalSeparator: ',' }
   }
}

Using...

{{ 12345 | currency }} // => R$ 12.345,00 (default)

Chaining Filters

Great module to easily grab some simple vue1 filters.. Works as expected, but how can we chain several filters. Specifically I'm working with an array,

<li v-for="workOrder in orderBy(workOrders, orderTerm, orderDesc)">

works great but I also need to add a "filterBy".. I tried pipes but no go.. Please let me know what the correct sintax would be!

Thanks

how to use currency in the methods?

so i do know that we can do it like this in filters

// in my app.js
Vue.filter('date', function(value){
    return window.moment(value).format('DD-MM-YYYY');
});

and i just create a function in my component

// in my component
formatDate(value){
 return Vue.filter('date')(value);
}

and back to the same place i can just do like this

<div v-tooltip:top=" formatDate(props.value)"> // working fine
{{ props.value | date) }} // working fine
</div>

but i tried the same way as

// in my component
formatCurrency(value){
 return Vue.filter('currency')(value)('',0,{ thousandsSeparator: '.'});
}

and then

<div v-tooltip:top=" formatCurrencyprops.value)"> // not working
{{ props.value | currency('',0,{ thousandsSeparator: '.'}) }} // working fine
</div>

so how to fix it? i need the same filters in there

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.