How to listen for 'props' changes

前端 未结 13 1495
无人及你
无人及你 2020-11-30 17:27

In the VueJs 2.0 docs I can\'t find any hooks that would listen on props changes.

Does VueJs have such hooks like onPropsUpdated() or simi

相关标签:
13条回答
  • 2020-11-30 18:19

    if myProp is an object, it may not be changed in usual. so, watch will never be triggered. the reason of why myProp not be changed is that you just set some keys of myProp in most cases. the myProp itself is still the one. try to watch props of myProp, like "myProp.a",it should work.

    0 讨论(0)
  • 2020-11-30 18:21

    The watch function should place in Child component. Not parent.

    0 讨论(0)
  • 2020-11-30 18:23

    I work with a computed property like:

        items:{
            get(){
                return this.resources;
            },
            set(v){
                this.$emit("update:resources", v)
            }
        },
    

    Resources is in this case a property:

    props: [ 'resources' ]
    
    0 讨论(0)
  • 2020-11-30 18:26

    You can watch 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>

    0 讨论(0)
  • 2020-11-30 18:28

    @JoeSchr has an answer. Here is another way to do if you don't want deep: true

     mounted() {
        this.yourMethod();
        // re-render any time a prop changes
        Object.keys(this.$options.props).forEach(key => {
          this.$watch(key, this.yourMethod);
        });
      },
    
    0 讨论(0)
  • 2020-11-30 18:30

    for two way binding you have to use .sync modifier

    <child :myprop.sync="text"></child>
    

    more details...

    and you have to use watch property in child component to listen and update any changes

    props: ['myprop'],
      watch: { 
        myprop: function(newVal, oldVal) { // watch it
          console.log('Prop changed: ', newVal, ' | was: ', oldVal)
        }
      }
    
    0 讨论(0)
提交回复
热议问题