Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share filters between parent and child

Tags:

vue.js

//main js

window.chat = new Vue({
    el: '#Chat',
    components: {
        chat: Vue.extend(require('./../components/chat/component.vue'))
    },
    filters: {
        emoji: function(content){
            return content;
        }
    }
})

// chat script.js

module.exports = {
    components: {
        message: Vue.extend(require('./../components/message/component.vue'))
    }
}

// message template

<span>{{{ message.text | emoji }}}</span>

This stuff gives me

app-1.0.4.js:12304 [Vue warn]: Failed to resolve filter: emoji (found in component: <message>)

I tried $root.emoji and $root.filters.emoji just for the sake of trying but it didn't work.

So how can I make this work. I really want to keep the filter in main.js

like image 230
John Avatar asked May 06 '16 14:05

John


1 Answers

You could use a mixin (https://vuejs.org/guide/mixins.html):

mixins/filter-emoji.js:

module.exports = {
    filters: {
        emoji: function(content){
            return content;
        }
    }
 }

main.js

window.chat = new Vue({
    el: '#Chat',
    mixins: [
        require('./../components/chat/component.vue')
    ],
    components: {
        chat: Vue.extend(require('./../components/chat/component.vue'))
    },
});

message/component.vue:

module.export = {
    mixins: [
        require('./../components/chat/component.vue')
    ]
}

This is one of the ways to share filters accross certain components. If you need it more often, you could even register it globally (see documentation https://v1.vuejs.org/guide/custom-filter.html):

Vue.filter('emoji', function(content){
    return content;
});
like image 130
nils Avatar answered Nov 15 '22 11:11

nils