Vue3中使用component :is 加载组件
1.不使用setup语法糖,这种方式和vue2差不多,is可以是个字符串
(图片来源网络,侵删)
切换组件 import { ref } from 'vue' import Child1 from './Child1.vue' import Child2 from './Child2.vue' export default { components: { Child1, Child2 }, setup() { let currentComp = ref('Child1') // 切换组件 const compChange = () => { if(currentComp.value == 'Child1') { currentComp.value = 'Child2' }else { currentComp.value = 'Child1' } } return { currentComp, compChange } } }
2. 使用setup语法糖,这时候的is如果使用字符串会加载不出来,得使用组件实例
第一种方式
切换组件 import { ref } from 'vue' import Child1 from './Child1.vue' import Child2 from './Child2.vue' const flag = ref(true)
第二种方式
切换组件 import { shallowRef, ref } from 'vue' import Child1 from './Child1.vue' import Child2 from './Child2.vue' //这里用ref的话,vue给出警告Vue接收到一个组件,该组件被制成反应对象。这可能会导致不必要的性能开销,应该通过将组件标记为“markRaw”或使用“shallowRef”而不是“ref”来避免。 // 如果使用 markRaw 那么currentComp将不永远不会再成为响应式对象。 所以得使用 shallowRef let currentComp = shallowRef(Child1) // 切换组件 const compChange = () => { if(currentComp.value == Child1) { currentComp.value = Child2 }else { currentComp.value = Child1 } }
(图片来源网络,侵删)
(图片来源网络,侵删)
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...