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

Vue.js组件切换技术问询:如何通过主页面脚本实现两组件按钮切换?

Vue组件切换实现方案(针对你的代码修正)

你的代码存在的几个问题

  • App.vue中data的写法错误,Vue2里data必须是返回对象的函数,不能直接写对象
  • 模板里用了v-if="show"但data里没定义show变量,反而定义的selectedComp没在模板中使用
  • toggleDisplay方法接收参数,但按钮点击时没传参,逻辑和模板不匹配
  • Display.vue中的setTimeout写法错误,setTimeout不返回Promise,不能链式调用.then,而且你操作的this.img根本不存在,应该修改byteArray

两种可行的组件切换实现方式

方式一:用v-if/v-else控制组件显示隐藏

修改后的App.vue代码:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <!-- 根据selectedComp判断显示哪个组件 -->
    <HelloWorld v-if="selectedComp === 'HelloWorld'" msg="Welcome to Your Vue.js App"/>
    <Display v-else />

    <button @click="toggleDisplay">切换组件</button>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import Display from './components/Display.vue'

export default {
  name: 'App',
  components: {
    HelloWorld,
    Display
  },
  data() { // 修正data的写法
    return {
      selectedComp: "HelloWorld" // 默认显示HelloWorld
    }
  },
  methods: {
    toggleDisplay() { // 不需要传参,直接切换状态
      this.selectedComp = this.selectedComp === 'HelloWorld' ? 'Display' : 'HelloWorld'
    }
  }
}
</script>

方式二:使用Vue动态组件(更简洁)

动态组件是Vue官方推荐的组件切换方式,用<component :is="selectedComp">实现:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <!-- 动态组件,:is绑定要显示的组件名 -->
    <component :is="selectedComp" :msg="selectedComp === 'HelloWorld' ? 'Welcome to Your Vue.js App' : ''"/>

    <button @click="toggleDisplay">切换组件</button>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import Display from './components/Display.vue'

export default {
  name: 'App',
  components: {
    HelloWorld,
    Display
  },
  data() {
    return {
      selectedComp: "HelloWorld"
    }
  },
  methods: {
    toggleDisplay() {
      this.selectedComp = this.selectedComp === 'HelloWorld' ? 'Display' : 'HelloWorld'
    }
  }
}
</script>

同时修正Display.vue的错误

把里面的错误setTimeout代码改成:

created() {
  this.fetchByteArray();

  // 5秒后隐藏图片,2秒后再重新获取显示
  setTimeout(() => {
    this.byteArray = null;
    setTimeout(() => {
      this.fetchByteArray(); // 重新调用接口加载图片
    }, 2000);
  }, 5000);
}

另外,你的createImage计算属性返回的是HTML字符串,直接用{{ createImage }}会显示纯文本,要渲染HTML的话需要用v-html="createImage",不过你已经直接用<img :src="byteArray" />了,这个计算属性可以删掉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:25:28