[Vuejs]-Is it possible to trigger a function upon some Vue data elements change?

0👍

You can use watchers for this.

<script>
    const SomeComponent = {
        name: 'SomeComponent',
        data() {
            someData: null,
        },
        watch: {
            'someData': {
                handler(newValue, oldValue) { // sets off when `someData` changes
                    this.someMethod();
                },
                immediate: true, // if you also want to execute the handler above on creation of the component
            },
        },
        methods: {
            someMethod() {
                // do something with this.someData
            }
        }
</script>

Sadly, you have to add a watcher for every data element that you want to watch, even if you want to execute the same function. If you want to avoid this you can create an object in your data, put your data inside this object and watch this object. You then need to pass deep: true at the watcher (like we did with immediate in the example above). This will watch for all changes on the object and trigger the method accordingly.

Leave a comment