经过几个小时的努力,终于实现了,根据组件名异常加载组件,直接上代码,网上的很多代码方都有坑,先贴出比较坑的代码:
<template>
<view class="main">
<view class="tops">
<view class="info">
<view class="item">
<view class="tit">姓名:</view>
<view class="txt">{{qyUser.name}}</view>
</view>
</view>
</view>
<view>
<component :is="dycomp" v-if="isShow"></component>
</view>
</view>
</template>
<script setup>
import { ref, defineAsyncComponent,markRaw } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import api from '../../api/api.js';
const qyUser = ref({});
//markRaw方法将组件对象标记为非响应式对象
//shallowRef代替ref来创建一个浅响应式对象
const dycomp = ref(null);
const isShow = ref(false);
onLoad(()=>{
geQyUserInfo();
loadAsyncComponent("mdIndex");
});
const loadAsyncComponent = (componentName)=>{
console.log(componentName);
dycomp.value = defineAsyncComponent(() =>{
import("../components/"+componentName+".vue");
}
);
isShow.value = true;
}
const geQyUserInfo = ()=>{
console.log(uni.getStorageSync("qyuserid"));
api.geQyUserInfo({
"qyuserid":uni.getStorageSync("qyuserid"),
},(res)=>{
qyUser.value = res.data.qyUser;
});
}
</script>
<style lang="scss" scoped>
.main {
background-color: #f5f6f8;
width: 100%;
height: 100vh;
box-sizing: border-box;
padding: 20rpx;
.tops {
background: #fff;
border-radius: 20rpx;
padding: 20rpx 20rpx 10rpx;
.title {
margin-bottom: 25rpx;
border-left: 6rpx solid #1296db;
padding-left: 10rpx;
}
.info {
.item {
display: flex;
align-items: center;
font-size: 26rpx;
margin-bottom: 10rpx;
.tit {
flex: 1;
color: #666;
}
.txt {
flex: 4;
}
}
}
}
}
</style>
最后优化后成功异步加载组件的代码:
<template>
<view class="main">
<view class="tops">
<view class="info">
<view class="item">
<view class="tit">姓名:</view>
<view class="txt">{{qyUser.name}}</view>
</view>
</view>
</view>
<view>
<component :is="dycomp" v-if="isShow"></component>
</view>
</view>
</template>
<script setup>
import { ref, defineAsyncComponent,markRaw,shallowRef } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import api from '../../api/api.js';
const qyUser = ref({});
//markRaw方法将组件对象标记为非响应式对象
//shallowRef代替ref来创建一个浅响应式对象
const dycomp = shallowRef(null);
const isShow = ref(false);
onLoad(()=>{
geQyUserInfo();
});
const loadAsyncComponent = (componentName)=>{
console.log(componentName);
dycomp.value = defineAsyncComponent({
loader: () => import("../../components/"+componentName+".vue"),
delay: 200,
timeout: 3000
}
);
isShow.value = true;
}
const geQyUserInfo = ()=>{
api.geQyUserInfo({
"qyuserid":uni.getStorageSync("qyuserid"),
},(res)=>{
qyUser.value = res.data.qyUser;
loadAsyncComponent("mdIndex");
});
}
</script>
<style lang="scss" scoped>
.main {
background-color: #f5f6f8;
width: 100%;
height: 100vh;
box-sizing: border-box;
padding: 20rpx;
.tops {
background: #fff;
border-radius: 20rpx;
padding: 20rpx 20rpx 10rpx;
.title {
margin-bottom: 25rpx;
border-left: 6rpx solid #1296db;
padding-left: 10rpx;
}
.info {
.item {
display: flex;
align-items: center;
font-size: 26rpx;
margin-bottom: 10rpx;
.tit {
flex: 1;
color: #666;
}
.txt {
flex: 4;
}
}
}
}
}
</style>