【问题标题】:Vuejs how to pass image url as prop to be used as css variable for css animationVuejs如何将图像url作为prop传递以用作css动画的css变量
【发布时间】:2020-04-24 15:43:24
【问题描述】:

我有一个具有悬停动画的组件,其中 4 个图像循环旋转:

animation: changeImg-1 2.5s linear infinite;

@keyframes changeImg-1 {
  0%, 100% { background-image: url('images/wel1.png'); }
  25% { background-image: url('images/wel2.png'); }
  50% { background-image: url('images/wel3.png'); }
  75% { background-image: url('images/wel4.png'); }
}

现在我想通过能够将图像字符串作为道具传递来使这个组件可重用,这些字符串被分配为 css 变量,然后被动画拾取。

我已经用计算属性中的路径定义了 css 变量,然后在 css 中使用:

computed: {
    userStyle () {
      return {
        '--myBackground': `url(${require('@/components/ImagesInText/images/wel1.png')})`,
      }
    }
  },

CSS:

.image {  
background:var(--myBackground); 
}

我无法开始工作的是从道具中获取图像路径并在计算属性中使用它......

   props: {
    image: { type: String, default: '@/components/ImagesInText/images/wel1.png' },
  },

如果我在下面执行此操作,我会收到错误消息:找不到模块 '@/components/ImagesInText/images/wel1.png'"

computed: {
    userStyle () {
      return {

        '--myBackground': `url(${require( this.image )})`,
      }
    }
  },

【问题讨论】:

    标签: css vue.js


    【解决方案1】:

    当使用变量路径/文件名时,require 需要一些帮助。您必须至少将路径的第一部分硬编码为字符串。

    • 例如,这有效:
    const filename = 'wel1.png';
    require('@/components/ImagesInText/images/' + filename); // <-- The string is needed
    
    • 这也有效:
    const path = 'components/ImagesInText/images/wel1.png';
    require('@/' + path); // <-- This is good enough too
    
    • 但这行不通:
    const fullpath = '@/components/ImagesInText/images/wel1.png';
    require(fullpath); // <-- No. Can't infer the path from a variable only
    

    【讨论】:

      【解决方案2】:

      正如this线程中提到的方式。它非常适合我。

      <div class="register-img" :style="{'background-image': 'url(' + require('@/assets/images/register-image.png') + ')'}"></div> 
      

      【讨论】:

        猜你喜欢
        • 2021-06-28
        • 2022-01-22
        • 2021-10-26
        • 1970-01-01
        • 2020-05-26
        • 2020-06-13
        • 2017-07-04
        • 2013-10-17
        • 1970-01-01
        相关资源
        最近更新 更多