vue中父子组件通过props传递数据,父组件数据更新,子组件不动态更新的解决方案

父组件:

  查看

    
    
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里面的方法。

你可能感兴趣的:(前端,vue.js)