Wells
Wells

Reputation: 10969

vuejs: filters in external file?

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?

Upvotes: 6

Views: 3712

Answers (3)

tianzhipeng
tianzhipeng

Reputation: 2209

Its in vuejs 1.0. Two-way filter has been removed from vuejs 2.0.

see git issue discuss and solution

Upvotes: 0

Joel Rocha
Joel Rocha

Reputation: 31

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

Upvotes: 3

Bert
Bert

Reputation: 82489

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.

Upvotes: 1

Related Questions