how to listen `props` changes ?

how to listen `props` changes ?

Asked on November 13, 2018 in vue.js.
Add Comment


  • 2 Answer(s)

    watch the props to execute some code upon props changes

    new Vue({
        el: '#app',
        data: {
            text: 'Hello'
        },
        components: {
            'child' : {
                 template: `<p>{{ myprop }}</p>`,
                 props: ['myprop'],
                 watch: {
                     myprop: function(newVal, oldVal) { // watch it
                         console.log('Prop changed: ', newVal, ' | was: ', oldVal)
                        }
                    }
                }
            }
        });
    
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <div id="app">
        <child :myprop="text"></child>
        <button @click="text = 'Another text'">Change text</button>
    </div>
    
    Answered on November 13, 2018.
    Add Comment

    Do tried this ?

    watch: {
        myProp: {
            // the callback will be called immediately after the start of the observation
            immediate: true,
            handler (val, oldVal) {
                // do your stuff
            }
        }
    }
    

     

    Answered on November 13, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.