vue中静态资源文件中的图片element.style.backgroundImage设置url无效问题

静态文件中的图片直接通过以下这种方式是无效的

element.style.backgroundImage = 'url("@/assets/img/btn_checkbox_nor@2x.png")';

但是在css中可以这样设置,这样设置会出现webpack打包找不到的问题

...
</script>
<style lang='less' scoped>
 .choose-item-img {
          background-image: url("../assets/img/btn_checkbox_nor@2x.png");
          background-repeat: no-repeat;
          background-position: -6px -6px;
          background-size: 24px 24px;
  }
</style>

非静态可以这样设置

<div :style="{backgroundImage: 'url(' + img + ')'}">
</div>
<div :style="{backgroundImage:`url(${img})`}">
</div>

js设置的方法需要通过引入

choicePerson(event) {
      this.isChoice = !this.isChoice;
      if (!this.isChoice) {
        event.currentTarget.style.width = '12px';
        event.currentTarget.style.height = '12px';
        event.currentTarget.style.backgroundPosition= '-6px -6px';
        // 这里可以通过require导入
        event.currentTarget.style.backgroundImage= 'url('+require('@/assets/img/btn_checkbox_nor@2x.png')+')';
      } else {
        event.currentTarget.style.width = '16px';
        event.currentTarget.style.height = '16px';
        event.currentTarget.style.backgroundPosition= '-4px -4px';
        event.currentTarget.style.backgroundImage= 'url('+require('@/assets/img/btn_checkbox_sel@2x.png')+')';
      }
    },

参考文章
https://blog.csdn.net/qq_43248623/article/details/107719794

https://blog.csdn.net/u013262823/article/details/86718145?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

https://www.cnblogs.com/qiuyueding/p/8953396.html#_label0

https://blog.csdn.net/qq_32682301/article/details/116050506

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值