vue3动态组件组件shallowRef包裹问题

在vue3做tabs切换功能的时候,如果导入的组件不适用shallowRef包裹会显示下面的警告:

Home.vue?t=1708401434509:43 [Vue warn]: Vue received a Component that was made a reactive object. This can lead to unnecessary performance overhead and should be avoided by marking the component with `markRaw` or using `shallowRef` instead of `ref`. 
Component that was made reactive:  {__hmrId: '2afd162d', __file: 'D:/v3code/my-big-charts/src/components/Comp7.vue', render: ƒ} 
  at <Home onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< Proxy(Object) {__v_skip: true} > > 
  at <RouterView> 
  at <App>

根据提示代码修改如下:

<script setup>
import {ref,reactive,readonly,computed,watch,watchEffect,markRaw,shallowRef} from 'vue'
import Comp7 from '../components/Comp7.vue'
import Comp6 from '../components/Comp6.vue'
const activeComp = shallowRef(Comp6)
const tab = reactive([{
    name: "A组件",
    comName: shallowRef(Comp6)
}, {
    name: "B组件",
    comName: shallowRef(Comp7
}])
const change = index=>{
    activeComp.value = tab[index].comName
}
</script>
<template>
    <ul>
        <li v-for="(item,index) in tab" :key="item.name" @click="change(index)">{{ item.name }}</li>
    </ul>
    <div>
        <component :is="activeComp"></component>
    </div>
</template>

就能解决上面的问题。

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你好!学习Vue 3动态组件是一个很不错的选择。Vue 3中的动态组件可以帮助你在运行时动态地切换不同的组件,并且非常方便易用。下面是一些学习Vue 3动态组件的基本步骤: 1. 安装Vue 3:首先,你需要在你的项目中安装Vue 3。你可以通过CDN引入Vue 3,也可以使用npm或yarn安装。 2. 创建动态组件:在Vue 3中,你可以使用`<component>`元素来创建动态组件。你可以将`is`属性设置为一个变量,该变量的值可以是一个组件的名称或组件实例。 3. 切换组件:通过改变`is`属性的值,你可以在运行时动态地切换组件。这可以通过计算属性、方法等来实现。 4. 注册组件:在使用动态组件之前,你需要确保你的组件已经注册。你可以使用`app.component`方法来全局注册组件,或者在局部组件中使用`components`选项来注册组件。 5. 渲染动态组件:最后,在模板中使用`<component>`元素并将`is`属性绑定到变量,以渲染动态组件。 这是一个简单的示例代码,演示了如何使用Vue 3动态组件: ```javascript <template> <div> <component :is="currentComponent"></component> <button @click="toggleComponent">切换组件</button> </div> </template> <script> import ComponentA from './ComponentA.vue'; import ComponentB from './ComponentB.vue'; export default { data() { return { currentComponent: 'ComponentA' }; }, components: { ComponentA, ComponentB }, methods: { toggleComponent() { this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'; } } }; </script> ``` 在这个示例中,我们创建了两个组件`ComponentA`和`ComponentB`,然后在父组件中使用`<component>`元素来动态渲染当前的组件。通过点击按钮,可以切换当前组件的显示。 希望这个示例能够帮助你开始学习Vue 3动态组件!如果你有任何问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_45925246

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值