【问题标题】:How to monitor the data changes of the parent component in the child component如何在子组件中监听父组件的数据变化
【发布时间】:2021-08-10 11:29:12
【问题描述】:

当父组件的数据发生变化时,如何在子组件中实现实时监控和响应。

【问题讨论】:

标签: vue.js


【解决方案1】:
props: ["opType", "editData"],
watch: {
  editData: {
    immediate: true,
    handler(newVal, oldVal) {
      if (this.editData.pryType === "MOBN") {
        this.infoIndex = 0;
      } else if (this.editData.pryType === "EMAL") {
        this.infoIndex = 1;
      } else if (this.editData.pryType === "SVID") {
        this.infoIndex = 2;
      } else if (this.editData.pryType === "BBIN") {
        this.infoIndex = 3;
        if (this.getListSeconed) {
          this.getkList();
          this.getListSeconed = false;
        }
      }
    },
    deep: true
  }
},

可以这样试试。

【讨论】:

    【解决方案2】:

    道具变化时可以观看道具:

    <div id="app">
      <childcomponent :myprop="text"></childcomponent>
      <button @click="text = 'New text'">Change text</button>
    </div>
    

    使用 watch 方法观察 ChildComponent 的变化!

    new Vue({
      el: '#app',
      data: {
        text: 'This is Text'
      },
      components: {
        'childcomponent' : {
         template: `<p>{{ myprop }}</p>`,
         props: ['myprop'],
         watch: { 
          myprop: function(newValue, oldValue) { 
           console.log('Prop changed and new value is: ', newVal, ' | old value: ', oldValue);
            }
          }
        }
      }
    });
    

    https://vuejs.org/v2/api/#watch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 2021-11-02
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多