vue.js - 通过名称和属性盲动态加载 vuejs 组件
问题描述
我想在 vuejs CLI 中将组件动态加载为单个文件组件,在 ajax 请求之前,我不知道将加载哪个组件,并且在页面加载时无法加载 150 个组件。
这是 ajax 响应的示例:
[
{is="Title", text:"Hello World"},
{is:"Status", type:"info", text:"Look at these beautiful photos"},
{is:"Carousel", imgs:["/img/1.jpg","/img/2.jpg","/img/3.jpg"]},
{is:"Status", type:"alert", text:"These images are the property of the creator"},
]
我想要一个像这样呈现的 vue 组件:
<template>
<component is="Title" text="Hello World"/>
<component is="Status" type="info" text="Look at these beautiful photos"/>
<component is="Carousel" imgs="['/img/1.jpg','/img/2.jpg','/img/3.jpg']"/>
<component is="Status" type="alert", text="These images are the property of the creator"/>
</template>
<script>
import Title from '@/components/libs/Title.vue'
import Status from '@/components/libs/Status.vue'
import Carousel from '@/components/libs/Carousel.vue'
export default {
components: {
Title,
Status,
Carousel
},
}
</script>
解决方案
应用程序.vue
<template>
<div id="app">
<DynamicComponentSet :definition="response"/>
</div>
</template>
<script>
import DynamicComponentSet from "@/components/DynamicComponentSet";
export default {
name: "App",
components: {
DynamicComponentSet
},
data() {
return {
response: [
{ is: "Title", text: "Hello World" },
{ is: "Status", type: "info", text: "Look at these beautiful photos" },
{ is: "Carousel", imgs: ["/img/1.jpg", "/img/2.jpg", "/img/3.jpg"] },
{
is: "Status",
type: "alert",
text: "These images are the property of the creator"
}
]
};
}
};
</script>
动态组件集.vue
<template>
<div>
<component v-for="(comp, index) in definition" :key="index" v-bind="comp" :is="comp.is"/>
</div>
</template>
<script>
export default {
name: "DynamicComponentSet",
components: {
Title: () => import("@/components/Title.vue"),
Status: () => import("@/components/Status.vue"),
Carousel: () => import("@/components/Carousel.vue")
},
props: {
definition: Array
}
};
</script>
注 1:is
必须在此处指定所有可能的值components
。组件按需加载(异步组件)。
注意 2:所有单个response
对象的属性都v-bind="comp"
使用props 作为对象语法传递到单个组件中,因此数据属性名称/类型必须与每个组件的 props 匹配......
注意 3::is="comp.is"
实际上不需要让它工作,因为它is
是与其他道具一起传递的。我补充说只是为了让 ESLint 开心......
推荐阅读
- rest - AzureDevops REST API - 如何取消特定部署
- dataframe - 无法通过 sas 中的 where 语句过滤我的数据集
- c++ - C++ Primer 第 14 章 readStr 示例无法在 Visual Studio 2019 中编译
- sql - 查找出售给“重新激活”客户的金额
- wpf - 如何在 Windows 服务中创建 WPF 调度程序
- python - 根据不同的列值删除 Pandas 中的 DF 行
- python - Pycharm 不显示 pynput 作为要安装的包
- c# - 如何在 ASP.NET 中使用 ConcurrentDictionary 和 Task
- php - 如何根据条件`+1`拆分数组?
- java - 调用意图过滤器时在其他应用程序上显示片段