Nuxt.js: Vue Filters

Created on 9 Feb 2017  Â·  26Comments  Â·  Source: nuxt/nuxt.js

Hello,

Where can i write the filters for the vue application? For ex:

Vue.filter('capitalize', val => val.toUpperCase())

Eariler it would reside in the main/app.js.

Thanks

This question is available on Nuxt.js community (#c195)
question

Most helpful comment

Hi @app-sparkler

Take a look at the plugins section of the documentation: https://nuxtjs.org/guide/plugins

You can have a filters.js file in your plugins directory:

import Vue from 'vue'

Vue.filter('capitalize', val => val.toUpperCase())

Then, in your nuxt.config.js:

module.exports = {
  plugins: ['~plugins/filters.js']
}

Nuxt.js will automatically import your file before creating the root instance.

All 26 comments

Hi @app-sparkler

Take a look at the plugins section of the documentation: https://nuxtjs.org/guide/plugins

You can have a filters.js file in your plugins directory:

import Vue from 'vue'

Vue.filter('capitalize', val => val.toUpperCase())

Then, in your nuxt.config.js:

module.exports = {
  plugins: ['~plugins/filters.js']
}

Nuxt.js will automatically import your file before creating the root instance.

Hi @Atinux

How about two-way filters? I'm following this migration guide and got some error.

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render. 
...
client.js:390 [nuxt.js] Cannot load components TypeError: Cannot set property 'value' of undefined
    at VueComponent.formatValue (currencyInput.js:81)
    at VueComponent.boundFn [as formatValue] (vue.runtime.common.js:127)
    at VueComponent.mounted (currencyInput.js:70)
    at callHook (vue.runtime.common.js:2754)
    at Object.insert (vue.runtime.common.js:1765)
    at invokeInsertHook (vue.runtime.common.js:4474)
    at VueComponent.patch [as __patch__] (vue.runtime.common.js:4638)
    at VueComponent.Vue._update (vue.runtime.common.js:2635)
    at VueComponent.updateComponent (vue.runtime.common.js:2609)
    at Watcher.get (vue.runtime.common.js:2934)

Can you provide code example to reproduce this error?

We can't help you without the reproduction.

On Wed, 15 Feb 2017 at 10:21, Aji Kisworo Mukti notifications@github.com
wrote:

Hi @Atinux https://github.com/Atinux

How about two-way filters? I'm following this migration guide
https://vuejs.org/v2/guide/migration.html#Two-Way-Filters-replaced and
got some error.

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside

, or missing . Bailing hydration and performing full client-side render.
...
client.js:390 [nuxt.js] Cannot load components TypeError: Cannot set property 'value' of undefined
at VueComponent.formatValue (currencyInput.js:81)
at VueComponent.boundFn [as formatValue] (vue.runtime.common.js:127)
at VueComponent.mounted (currencyInput.js:70)
at callHook (vue.runtime.common.js:2754)
at Object.insert (vue.runtime.common.js:1765)
at invokeInsertHook (vue.runtime.common.js:4474)
at VueComponent.patch [as __patch__] (vue.runtime.common.js:4638)
at VueComponent.Vue._update (vue.runtime.common.js:2635)
at VueComponent.updateComponent (vue.runtime.common.js:2609)
at Watcher.get (vue.runtime.common.js:2934)

—
You are receiving this because you were mentioned.

Reply to this email directly, view it on GitHub
https://github.com/nuxt/nuxt.js/issues/231#issuecomment-279958341, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AA3OFBViifJi1_QxAVo8zw4wPhXWQLGXks5rcsOBgaJpZM4L8wmu
.

I use this snippet

It should work without problem @Cengkaruk

Can you show your code your doing with Nuxt.js?

@Atinux
I has a same problem with use the v-html,like:

v-html="`${ post.abstract | marked }`"

but if I use {{post.abstract | marked}},it works

the vue devtools log:

vue.runtime.common.js:521[Vue warn]: Property or method "marked" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

@linsir indeed you should use:

v-html="{{ post.abstract | marked }}"

@Atinux This my plugin and i use it on the pages using this block of code.

<currency-input
    v-model="price"
  ></currency-input>

@Atinux But I try it ,it does not work, and the log:

Vue template syntax error:

- invalid expression: v-html="{{ post.abstract | marked }}"

and I try v-html="{{ post.abstract }}"

- invalid expression: v-html="{{ post.abstract }}"

but I try

v-html="`${ post.abstract }`"

it works.
Any thoughts?
Thanks

@linsir it should also work with :

v-html="post.abstract"

you don't need the ${...} since you're not _concatenating_ the string here..

Does it work?

v-html="post.abstract"

it does not work.

@linsir This issue is no longer regarding Vue-filters, i think you should go ahead and open a New Issue

@app-sparkler Sorry, I make a mistake.

v-html="post.abstract"

it works. But

v-html="post.abstract | marked"

it does not work.

@linsir you should use a computed property for v-html if you want to use a filter.

@linsir

Assuming what you are trying to bind to v-html is an html string and you want to apply some filter to it, i've tried this:

  • thtml is the custom directive we'll create _locally_
  • capitalize is the filter we will apply to it
<!-- TEMPLATE -->
 <template>
<div>
    <div v-thtml="testHtml" filters=" capitalize | pinkify "></div>
</div>
</template>

<!-- LOGIC -->
<script>
import $ from 'jquery'

export default {
  data () {
    return {
      testHtml: `
        <h1>Hello World</h1>
        <p>The world says hello!</p>
      `
    }
  },
  directives: {
    thtml: {
      inserted (el, bindings) {
        const template = $(bindings.value)
        let filters = el.attributes.filters || null
        filters = filters ? filters.value.split('|')
          .map(filter => filter.trim()) : []
        //
        if (filters.length) applyFilters()
        //
        function applyFilters () {
          filters.forEach(filter => {
            if (filter === 'capitalize') {
              template.css('text-transform', 'uppercase')
            }
            if (filter === 'pinkify') {
              template.css('color', 'deeppink')
            }
          })
        }
        template.appendTo(el)
      }
    }
  }
}
</script>

Please check it out and let me know if this serves your purpose.

INPUT

<div>
  <div v-thtml="testHtml" filters="capitalize | pinkify"></div>
</div>

testHtml - the html string we will apply the capitalize | pinkify filters on

<h1>Hello World!</h1><p>The world says hello!</p>

OUTPUT

image

Note

v-html is an inbuilt-directive and i think it will not allow filters, thus, we have to create a custom directive for the task.

Good Luck.

@Atinux Thanks.
@app-sparkler Because I use v-for, I use computed and Props (child component) to solve it.

reference: http://stackoverflow.com/questions/38799546/vue-js-get-v-for-array-value-in-computed

Ok @linsir :+1:

I've updated the answer in case you want to _apply_ filters on html strings.

Thanks.

@app-sparkler Okay, thank you.

Hi after upgrading to 2.0.1 my filter in my plugins is not working again....

@jeck5895 create a reproducible example on codesandbox or github repo

In my pluglins/filters.js
`import Vue from 'vue'

Vue.filter('toUrlFormat', param => {
let temp = param.replace(/[^a-zA-Z0-9\s-]/g, "");

return temp.replace(/\s+/g, "-").toLowerCase();
});
`

and in my nuxt.config.js
plugins: [ '@/plugins/filters.js', ]

@jeck5895 well, provide full not working example, because this code should work.

@jeck5895 its something with your filter regexps. https://codesandbox.io/s/0qjw35q3p - see here replaced your regex logic with simple return and ti work

@aldarund but its working if I'm putting it on function method.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mattdharmon picture mattdharmon  Â·  3Comments

vadimsg picture vadimsg  Â·  3Comments

pehbehbeh picture pehbehbeh  Â·  3Comments

vadimsg picture vadimsg  Â·  3Comments

surmon-china picture surmon-china  Â·  3Comments