Vue: Allow lifecycle creation hook functions to return callbacks that will be called when the component will be destroyed.

Created on 28 Feb 2020  Â·  2Comments  Â·  Source: vuejs/vue

What problem does this feature solve?

This allows to simplify code and makes unnecessary to move some variables out of lifecycle hooks scope.

I suppose that the callback returned by mounted hook may be called at beforeDestroy step, the callback returned by beforeMounted at destroyed.

I don't know if this could be used in creation and beforeCreate.

It's need to be discussed the way to combinate if both, the creation hooks return callback and the matching destruction hook are used.

What does the proposed API look like?

export default {
    data() {
        return {
            interval: null 
        }
    },
    mounted() {
        this.interval = setInterval(() => /* … */, 500)
    },

    beforeDestroy() {
        clearInterval(this.interval)
    },

  /*** PROPOSED FEATURE ***/
    mounted() {
        const interval = setInterval(() => /* … */, 500)

        // to be called at beforeDestroy
        return () => clearInterval(interval)
    }
}

Most helpful comment

FYI, you don't need to declare interval in data. Anything non-reactive doesn't need to be declared.

You can already do this by calling $on

mounted() {
        const interval = setInterval(() => /* … */, 500)
        this.$on('hook:beforeDestroy', () => clearInterval(interval))
    }

All 2 comments

FYI, you don't need to declare interval in data. Anything non-reactive doesn't need to be declared.

You can already do this by calling $on

mounted() {
        const interval = setInterval(() => /* … */, 500)
        this.$on('hook:beforeDestroy', () => clearInterval(interval))
    }

It should be added to the documentation.

Was this page helpful?
0 / 5 - 0 ratings