乐趣区

关于前端:vue中父子组件通过props传递数据父组件数据更新子组件不动态更新的解决方案

父组件:

  <a-button type="primary" @click="lookInterfaceInfo(record)"
            > 查看 </a-button
          >
<!-- 查看接口信息弹框 -->
    <look-interface v-if="flag" :interFaceProps="interFaceProps"  >
    </look-interface>
methods: {
    // 查看单个接口信息
    lookInterfaceInfo(value) {console.log(value, "lookInterfaceInfo");
         this.flag =true;
       this.interFaceProps.modelSwitch =true;
        this.interFaceProps.id= value.id;   
    },
  }

子组件:

export default {
  name: "lookInterface",
  props: ["interFaceProps"],
  components: {},
  data() {
    return {data: [],
    };
  },
  created() {},
  watch: {"interFaceProps.id": function (newValue, oldValue) {console.log(newValue, "newValue");
      console.log(oldValue, "oldValue");
      if (newValue) {const url = `/api/interface-api/getApi?id=${newValue}`;
        this.$Ajax.get(url).then((e) => {if (e.success) {console.log(e.success);
            this.data.push(e.result);
          }
        });
      } else {if (this.interFaceProps.id) {const url = `/api/interface-api/getApi?id=${this.interFaceProps.id}`;
          this.$Ajax.get(url).then((e) => {if (e.success) {// console.log(e.success);
              this.data.push(e.result);
            } else {this.data = [];
            }
          });
        }
      }
    },
  },
  mounted() {console.log(this.interFaceProps.id, "this.interFaceProps.id");
    this.getInterFaceinfo();},

 getInterFaceinfo() {const url = `/api/interface-api/getApi?id=${this.interFaceProps.id}`;
      this.$Ajax.get(url).then((e) => {if (e.success) {//console.log(e.success);
          this.data.push(e.result);
        } else {this.data = [];
        }
      });
    },

总结:

通过在子组件监听 props 外面 id 值变动,最开始启用 mounted 的办法,前面依据变动的 props 执行 watch 外面的办法。

退出移动版