父组件通过属性绑定更新了传递给子组件的prop属性 子组件却没有及时更新

问题

父组件通过props传递给子组件的值不是最新的

场景:父组件通过props向子组件传递了一个数组info,父组发请求后更改数组info,此时通过this.$refs.childName来操作子组件的数组info的值并非最新的值

代码详情

父组件:通过props向子组件传递了一个数组info

当我点击父组件的按钮时,发请求获取了数据并赋值给了info数组,点击事件代码在下面(解决修改代码过程)

  <div class="">
    <button @click="btnClick">发送get请求</button>
    <Child :info="infoList" ref="child" />
  </div>
  
  data() {
    return {
      infoList: [],
    };
  },

子组件:通过props接收了父组件传过来的数组;它后一个方法,获取最新的数组值

 props: ["info"],

  methods: {
    getNewestVal() {
      console.log(this.info);
    },
  },

解决修改代码过程

写法1:这是我一开始的写法,点击按钮后,打印出来的是初始值[]

然后我想到了同步异步的问题

    btnClick() {
      this.getReq();
      this.$refs.child.getNewestVal();
    },

    getReq() {
      axios.get("http://localhost:8080/api/contactList").then((res) => {
        this.infoList = res.data.data;
      });
    },

写法2:我先使用 this.$nextTick(() ,让它也变为异步,但是它是微任务,还是不行

    btnClick() {
      this.getReq();
        this.$nextTick(() => {
          this.$refs.child.getNewestVal();
        });
    },

    getReq() {
      axios.get("http://localhost:8080/api/contactList").then((res) => {
        this.infoList = res.data.data;
      });
    },

写法3:setTimeout变为异步

这样虽然可以解决,但是逻辑上是由问题的;如果请求时间长,就会出问题,这是一个隐藏的bug,使用setTimeout的时候一定要谨慎

    btnClick() {
      this.getReq();
      setTimeout(() => {
          this.$refs.child.getNewestVal();
      }, 1000);
    },

    getReq() {
      axios.get("http://localhost:8080/api/contactList").then((res) => {
        this.infoList = res.data.data;
      });
    },

写法4:我直接写在了getReq中,发现居然还不行,this.$refs操作是还没有更新

    btnClick() {
      this.getReq();
    },

    getReq() {
      axios.get("http://localhost:8080/api/contactList").then((res) => {
        this.infoList = res.data.data;
        this.$refs.child.getNewestVal();
      });
    },

下面的方法终于解决了:

写法5:;经过写法3、4,我终于感觉快解决了,给他加了this.$nextTick,这样问题解决了,只是getReq的目的不是很单纯

    btnClick() {
      this.getReq();
    },

    getReq() {
      axios.get("http://localhost:8080/api/contactList").then((res) => {
        this.infoList = res.data.data;
        this.$nextTick(() => {
          this.$refs.child.getNewestVal();
        });
      });
    },

写法6:使用async await也是一样的

    btnClick() {
      this.getReq();
    },

    async getReq() {
      const res = await axios.get("http://localhost:8080/api/contactList");
      this.infoList = res.data.data;
      this.$nextTick(() => {
        this.$refs.child.getNewestVal();
      });
    },

写法7:借助promise

    btnClick() {
      const p = this.getReq();
      p.then(() => {
        this.$refs.child.getNewestVal();
      });
    },

    async getReq() {
      const res = await axios.get("http://localhost:8080/api/contactList");
      this.infoList = res.data.data;
      return Promise.resolve();
    },

这只是一种写法,主要是针对这种写法的bug解决;我们当然可以通过eventBus在子组件中调用等……

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐