vue 根据对象key值替换字符串

该代码片段展示了在Vue.js中如何使用模板字符串和数据对象来动态替换模板中的变量,并在`mounted`生命周期钩子中执行替换操作。方法`replaceString`用于处理字符串中的占位符。
摘要由CSDN通过智能技术生成

在这里插入图片描述

在这里插入图片描述

<template>
  <div></div>
</template>
  
<script>
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {};
  },
  filters: {},
  computed: {},
  watch: {},
  created() {},
  mounted() {
    const res = {
      template: '床前明${name}\n疑是${start}${end}\n\n举头望${tit}\n低头思${text}\n',
      value: {
        end: '上霜',
        name: '月光',
        start: '地',
        text: '故乡',
        tit: '明月'
      }
    };
    for (const key in res.value) {
      res.template = this.replaceString(res.template, key, res.value[key]);
    }
    console.log(res.template)
  },
  beforeDestroy() {},
  methods: {
    replaceString(string, key, value) {
      let str = string;
      const type = '${' + key + '}';
      while (str.indexOf(type) !== -1) {
        str = str.replace(type, value);
      }
      return str;
    },
  },
};
</script>
  
<style scoped lang="less">

</style>
  
如果你需要在 Vue 表格中对字符串进行操作,可以使用 `computed` 计算属性来实现。 例如,假设我们有一个表格列 `description`,需要将其中的字符串中的大写字母转换为小写字母,并去掉空格和特殊字符。可以这样写: ```html <template> <div> <table> <thead> <tr> <th>Description</th> </tr> </thead> <tbody> <tr v-for="item in items" :key="item.id"> <td>{{ descriptionFormatted(item.description) }}</td> </tr> </tbody> <tfoot> <tr> <td>{{ descriptionSummary }}</td> </tr> </tfoot> </table> </div> </template> <script> export default { data() { return { items: [ { id: 1, description: 'This is a test' }, { id: 2, description: 'Another Test!' }, { id: 3, description: 'Testing 123' }, ], } }, computed: { descriptionSummary() { let summary = '' this.items.forEach((item) => { summary += item.descriptionFormatted.replace(/\s+/g, '') + ' ' }) return summary }, }, methods: { descriptionFormatted(description) { return description.toLowerCase().replace(/\s+/g, '').replace(/[^a-zA-Z0-9]/g, '') }, }, } </script> ``` 这里使用了 `descriptionFormatted` 方法来格式化 `description` 字符串,将其中的大写字母转换为小写字母,并去掉空格和特殊字符。在模板中使用 `{{ descriptionFormatted(item.description) }}` 来渲染表格数据。 另外,在表格的汇总列中,可以使用 `computed` 计算属性来计算汇总结果。在上面的例子中,我们使用 `descriptionSummary` 计算属性来计算所有 `description` 字符串的格式化结果,并将其拼接在一起。在模板中使用 `{{ descriptionSummary }}` 来渲染汇总结果。 注意,如果需要对字符串进行复杂的操作,建议使用正则表达式来实现。上面的例子中,我们使用了 `/[^a-zA-Z0-9]/g` 正则表达式来匹配除了字母和数字以外的字符,并将其替换为空字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值