html - VueJS - 调用多个图像 src 作为自定义道具
问题描述
我有一小部分图标,我想根据组件的项目类型将其称为自定义图像道具。代码如下所示:
Vue.component('otherArticles', {
template: `
<!-- Component -->
<li>
<img :src="icon.text && icon.video" alt="icon">
<a :href="url">{{ Title }}</a>
</li>
`,
props: {
title: String,
url: String,
icon: [
{
text: "/resources/img/icons/text-icon.svg",
video: "/resources/img/icons/video-icon.svg"
}
]
}
});
理想情况下,在我的 html 中,我想这样称呼它们:
<!--Component with text icon-->
<other-articles
icon='text' <!-- how i'd like to call the text icon as img src -->
url="."
title="Text article title">
</other-articles>
<!--Component with video icon-->
<other-articles
icon='video' <!-- how i'd like to call the video icon as img src -->
url="."
title="Video article title">
</other-articles>
我知道 img src 绑定不正确,我将其用作我认为应该如何完成的示例,但我正在寻找有关如何正确执行此操作的所有建议,因此我可以将其称为html 如示例所示。
我只有这两个图标,每个图标的 src 位置可能会改变,但我想以相同的方式调用它,即使我必须在将来更新任何一个的 src 位置,保持 html 调用相同或相似。任何帮助,将不胜感激。谢谢
解决方案
首先在你的数据函数中声明你的图标列表如下:
data() {
return {
iconList: {
text: '/resources/text.png',
video: '/resource/video.png',
}
};
}
确保删除列表并重命名对象,因为您不能在数据中拥有同名的道具和条目。然后将您的定义添加icon
到您的道具部分,如下所示:
props: {
icon: {
type: String,
required: true,
},
},
这告诉 Vue 将 prop 作为字符串进行类型检查,并在它不存在或不是字符串时发出警告。
现在你需要更新你的模板函数来使用这个新的道具作为键来查找相关的图标:
template: `
<img :src="iconList[icon]"/>
`,
现在您可以将组件用作<comp icon="video"/>
推荐阅读
- excel - 循环工作表中的范围并更新另一个范围
- python - 为什么 FAST/ORB 在寻找图像边缘附近的关键点方面不好
- angular - 用 Observable 替换 Promise
- javascript - 如何完全防止 Web 表单输入文本项更改
- html - 缩放 500% 时 svg 路径移动
- javascript - React:如何将服务器端 HTML 与 React 组件和函数混合使用
- reactjs - 反应具有相同名称的元素
- c++ - 如何在 C++ 中制作表示整数的链表?(LeetCode 加两个数字)
- docker - 当我构建 docker 镜像时,为什么会跳过多项选择题?(例如,安装 dnsutils 的地理区域)
- javascript - 如何在 html (js) 中的条目空间前面放置一个常数?