首页 > 解决方案 > 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 调用相同或相似。任何帮助,将不胜感激。谢谢

标签: htmlvue.jsvuejs2componentsvue-component

解决方案


首先在你的数据函数中声明你的图标列表如下:

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"/>


推荐阅读