【问题标题】:How to replace a slash in vue.js如何在 vue.js 中替换斜线
【发布时间】:2021-12-10 11:40:18
【问题描述】:

我的代码有点问题:

<template slot="popover">
  <img :src="'img/articles/' + item.id + '_1.jpg'">
</template>

我的一些 item.id 编号中有一个斜线。因此,某些图像无法显示。现在,如果 item.id 编号中出现斜线,我想用下划线替换斜线或将其删除。有没有简单的解决方案?

斜线应该只在代码中的这一点被替换,而不是在使用 item.id 的其他地方。

【问题讨论】:

  • 使用函数在内部处理这个问题:&lt;img :src="'img/articles/' + handleSlash(item.id) + '_1.jpg'"&gt;
  • 你用的是哪个vue版本?
  • 我使用的是 16.11.1 版本

标签: javascript vue.js


【解决方案1】:

您可以使用计算属性并将斜杠替换为 replace 和正则表达式:

<template slot="popover">
  <img :src="`img/articles/${itemId}_1.jpg`">
</template>

<script>
...
  computed: {
    itemId: function(){
        return this.item.replace(/\//g, '-');
    }
  }
...
</script>

这是一个测试小提琴:https://jsfiddle.net/pqfvba6n/

【讨论】:

  • 我在示例中使用破折号,但您可以使用任何其他字符,例如像 this.item.replace(/\//g, '_') 这样的下划线或像这样删除斜杠 this.item.replace(/\//g, '')
  • 我使用 :src="`img/articles/${itemId}_1.jpg`" 而不是 :src="'img/articles/' + itemId + '_1.jpg'" 因为我觉得它更简洁,但你可以保留你的版本
【解决方案2】:

使用replace (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

<template slot="popover">
  <img :src="'img/articles/' + item.id.replace(/\//g, '_') + '_1.jpg'">
</template>

【讨论】:

  • 如果有很多斜线,它只会替换第一个,这就是为什么我使用带有g标志的正则表达式
  • 问题提到“斜线”而不是“斜线”,所以应该用.replace("/", "_") 覆盖虽然我确实编辑了我的答案以使用正则表达式,谢谢
猜你喜欢
  • 1970-01-01
  • 2013-09-20
  • 2014-01-11
  • 1970-01-01
  • 2011-12-22
  • 2014-09-09
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多