You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue仅使用mixins场景下判断外部组件加载完成并获取其imgUrl数据

实现方案

你可以通过在全局mixin中扩展存储字段、利用$root访问根实例的特性实现需求,无需额外新增主组件逻辑,也不受actions-comp嵌套层级限制,修改后的代码如下:

1. 扩展全局mixin

const globalMixin = {
  data(){
    return {
        displayDetails:{
          show:false,
          imgUrl: '' // 新增字段存储生成的图片地址
        }
    }
  },
  methods: {
    // 新增方法接收display-comp回传的图片地址
    setDisplayImgUrl(url) {
      this.displayDetails.imgUrl = url
    }
  }
}

2. 修改display-comp逻辑,生成地址后回传根组件

const comp3 = {
  name:'display-comp',
  template:`<img src="" id="img" width="150px" height="80px" style="border:1px solid red;"/>`,
  data(){
    return {
        imgUrl:'',
        imgLoaded:false,
    }
  },
  mounted(){
    // 模拟服务端异步返回
    setTimeout(() => {
      this.imgUrl = `https://via.placeholder.com/150`
      this.$nextTick(() => {
        document.getElementById('img').setAttribute('src',this.imgUrl);
        this.imgLoaded = true;
        // 回传地址到根组件
        this.$root.setDisplayImgUrl(this.imgUrl)
      });
    }, 500);
  },
  beforeDestroy(){
     this.imgLoaded = true;
  }
}

3. 修改actions-comp逻辑,监听根组件的图片地址变化

const comp2 = {
  name:'actions-comp',
  template:`<button @click="displayThumbnail()">生成并展示图片</button>`,
  watch: {
    // 监听根组件存储的图片地址,赋值完成后自动触发后续逻辑
    '$root.displayDetails.imgUrl'(newVal) {
      if(newVal) {
        console.log('display-comp的图片地址为:', newVal)
        // 此处可执行地址上报、发送等后续业务逻辑
      }
    }
  },
  methods:{
    displayThumbnail(){
      // 点击时先重置旧地址,避免复用上次的结果
      this.$root.displayDetails.imgUrl = ''
      this.$root.displayDetails.show = true
    }
  }
}

4. 修复原HTML的标签语法错误

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <display-comp v-if="displayDetails.show" ref="display"></display-comp>
  <actions-comp></actions-comp>
</div>

内容的提问来源于stack exchange,提问作者EaBengaluru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:24:01