Vue: There is something wrong with vue filters

Created on 6 Mar 2017  ·  4Comments  ·  Source: vuejs/vue

code

<template>
    <div class="">
        <p @click="dodo">{{aa}}</p>
        <p @click="dodo1">{{mess | sum}}</p>
    </div>
</template>
<script type="text/javascript">
export default {
    data: function() {
        return {
            aa: [1],
            mess: 1
        }
    },
    methods: {
        dodo() {
            this.aa.push(1);
        },
        dodo1() {
            this.mesaa ++;
        },
    },
    filters: {
        sum(v) {
            console.log(2333);
            return v + 1;
        }
    }
</script>

When I click on the event dodo, the console output 2333.
Expect it to have no output.

All 4 comments

I think that is because of vdom have to run the filter to compare it against.

Filters are supposed to be pure functions, though javascript doesn't enforce them to be pure. So it's your responsibility to remove all side effects (e.g. console.log).

@fnlctrl but, when I reset "this.aa" , all filters functions will execution. Whether this will waste efficiency

Filters are always called whenever the render function is called, and render function calls can be triggered by any state change.
If you care about performance, use computed properties instead of filters - they are called only when the value they depend on changes (you can consider this as automatic caching).

Was this page helpful?
0 / 5 - 0 ratings