Home > Mobile >  how to use watch properly
how to use watch properly

Time:12-01

I am sending props month_id to child component from parent component by clicking on a <li>. My child component code is like below.

<script>
    export default {
        props: ['mosque_id', 'month_id'],
        data(){
            return {
                prayer_times: [],
            }
        },
        watch: {
            month_id() {
                this.getPrayerTime();
            }
        },
        methods:{
            getPrayerTime: function () {
                axios.get('/api/v1/getPrayerTime/'  this.mosque_id '/'  this.month_id)
                .then(function (response) {
                    this.prayer_times = response.data;
                }.bind(this));
            }
        },
    }
</script>

But I am getting result little late. I have to click twice on <li> to get result. Am I using watch properly ?

CodePudding user response:

Add immediate:true option to run the watch at the first rendering, also change function (response) { to (response)=> { in order to get access to this :

   watch: {
            month_id: {
              handler(){
                  this.getPrayerTime();
                },
               immediate : true 
            }
        },
    methods:{
            getPrayerTime: function () {
                axios.get('/api/v1/getPrayerTime/'  this.mosque_id '/'  this.month_id)
                .then((response)=> {
                    this.prayer_times = response.data;
                }.bind(this));
            }
        },

CodePudding user response:

You can receive the new value in your watch function and send it to yout getPrayerTime function

watch: {
    month_id(newValue, oldValue): {
        this.getPrayerTime(newValue);
    },
}

I think this can help you.

  • Related