Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs: filters in external file?

Tags:

vue.js

src/app.js looks like:

import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource';

Vue.use(VueRouter);
Vue.use(VueResource);

const app = require("./app.vue");
const f = require('./filters');

const router = new VueRouter({
    routes: [
        {name: 'home', path: '/', component: home}
    ]
});

new Vue({
    router: router,
    filters: f,
    render: h => h(app)
}).$mount("#app");

src/filters/index.js looks like:

module.exports = {
    season: (value) => {
        return 'foo';
    }
}

Using webpack to roll it up, but the filter doesn't work and Vue warns me like so:

build.js:830 [Vue warn]: Failed to resolve filter: season
(found in <Anonymous>)

How can I properly put my filters in a separate file?

like image 856
Wells Avatar asked Jun 27 '17 17:06

Wells


2 Answers

You can loop all filters from an array created inside your file for example.

const filters =
[
   {
     name: 'season',
     execute: (value) => { return 'foo'; }
   }
]

export default filters

And in you main.js you do the loop,

import filters from './filters'

filters.forEach(f => {
   Vue.filter(f.name, f.execute)
})

[]s

like image 106
Joel Rocha Avatar answered Nov 15 '22 13:11

Joel Rocha


You are not registering that filter globally, you are only registering it to be used in the template of #app. But your app immediately renders the component, app.

To make the season filter available globally, use

Vue.filter("season", f.season)

in your app.js.

Or you can import the filters into the components that use them.

like image 22
Bert Avatar answered Nov 15 '22 12:11

Bert