vue.js - 为什么动态组件在 vue3 中不起作用?
问题描述
这是一个有效的 Vue2 示例:
<template>
<div>
<h1>O_o</h1>
<component :is="name"/>
<button @click="onClick">Click me !</button>
</div>
</template>
<script>
export default {
data: () => ({
isShow: false
}),
computed: {
name() {
return this.isShow ? () => import('./DynamicComponent') : '';
}
},
methods: {
onClick() {
this.isShow = true;
}
},
}
</script>
在 Vue3 选项下重做不起作用。不会发生错误,但不会出现组件。
<template>
<div>
<h1>O_o</h1>
<component :is="state.name"/>
<button @click="onClick">Click me !</button>
</div>
</template>
<script>
import {ref, reactive, computed} from 'vue'
export default {
setup() {
const state = reactive({
name: computed(() => isShow ? import('./DynamicComponent.vue') : '')
});
const isShow = ref(false);
const onClick = () => {
isShow.value = true;
}
return {
state,
onClick
}
}
}
</script>
有人研究过vue2 beta版吗?请帮帮我。抱歉语言笨拙,我使用谷歌翻译。
解决方案
将模板中的所有内容都保留在 Vue2 中
<template>
<div>
<h1>O_o</h1>
<component :is="name"/>
<button @click="onClick">Click me !</button>
</div>
</template>
仅在“设置”中使用 defineAsyncComponent 进行更改
您可以在此处了解有关 defineAsyncComponent 的更多信息 https://labs.thisdot.co/blog/async-components-in-vue-3
const isShow = ref(false);
const name = computed (() => isShow.value ? defineAsyncComponent(() => import("./DynamicComponent.vue")) : '')
const onClick = () => {
isShow.value = true;
}
推荐阅读
- angularjs - Angularjs 承诺?
- reactjs - 我可以在使用 Firebase 身份验证时修复“无法在现有状态转换期间更新”错误吗?
- xcode - 如何将颤振应用程序从 android studio 导出到 Xcode?
- html - 如何获得顶部元素,例如 xpath 上元素的前面?
- angular - Angular - 使用服务将组件插入到另一个组件中
- php - 使用php中的Gmail API发送超过5 MB大小的附件时获取请求实体太大错误413
- c# - Razor 页面,如何使用标签助手 asp.net 核心进行路由
- python - 如何修复此错误 'numpy.ndarray' 对象在下面的代码中没有属性 'append'
- javascript - 记录更新后组件不会重新呈现
- alexa - Alexa Skill - 有可能得到用户所说的吗?