Pds Ink
Pds Ink

Reputation: 765

vuejs - how to use watch with props?

i am trying to access to a props data to use within a watch method in vue js, but apparently seems to do anything, here what i have done:

HTML

                <lista-servizi-blu 
                :servizi="modello" 
                :extdesktop="servizi_selezionati_desktop" 
                v-on:centramappa="mappaCenter($event)" 
                v-on:linebigger="inebigger($event)">
                </lista-servizi-blu>

JAVASCRIPT (COMPONENT)

props: ['servizi','extdesktop'],
    watch: {
    extdesktop: function(val, oldVal){
        alert(val);
        this.mostraDescLungaBlu();
    }
}

the alert seems not to be triggered, how can i solve this? thank you in advance

Upvotes: 0

Views: 4009

Answers (1)

Thusitha
Thusitha

Reputation: 3511

extDesktop watch won't fire on the Vue component init process. It will only trigger if you change the value later from somewhere.

Look at the following example

new Vue({
  el: '#app',
  data: {
    text: 'Hello'
  },
  components: {
    'child' : {
      template: `<p>{{ extdesktop }}</p>`,
      props: ['extdesktop'],
      watch: { 
      	extdesktop: function(newVal, oldVal) {
          // watch it
          alert('Prop changed: ' + newVal + ' | was: ' + oldVal);
          console.log('Prop changed: ', newVal, ' | was: ', oldVal)
        }
      }
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <child :extdesktop="text"></child>
  <button @click="text = 'Another text'">Change text</button>
</div>

Upvotes: 4

Related Questions