Vuejs: filters in external file?

src/app.js

as follows:

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

as follows:

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

      

Using webpack

to collapse it, but the filter doesn't work and Vue warns me like this:

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

      

How to put filters in a separate file correctly?

+3


source to share


3 answers


You are not registering this filter globally, you are only registering it in the template #app

. But once your application displays the component app

.

To make the filter season

available globally, use

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

      



in app.js.

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

0


source


You can loop all filters from an array created in your file eg.

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

export default filters

      

And in you main.js you do a loop,



import filters from './filters'

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

      

[] S

+1


source


Its in vuejs 1.0. The two way filter has been removed from vuejs 2.0.

see git discuss the question and solution

0


source







All Articles