【问题标题】:How to add a html class in a Vue data string?如何在 Vue 数据字符串中添加 html 类?
【发布时间】:2019-09-18 03:38:54
【问题描述】:

我在 Vue 中有一个组件,我有一些硬编码数据。我需要将font-bold uppercase 类添加到字符串中的一个单词中。

如何在 Vue 中实现这一点?

在下面的代码中,在data > need 中,您将看到单词HOPE。我需要这个词来上课。

export default {

    data: function() {
        return {
            locations: [{
                    id: 1,
                    name: 'Example',
                    need: "Lorem ipsum HOPE dolor sit amet.",
                },
                {
                    id: 2,
                    name: 'Example 2',
                    need: "Morbi et lobortis ante, HOPE eu viverra quam.",

                },

              ]
            }
        }
    }

HTML:

<template>
    <div>
        <div v-for="(location, index) in locations">
            <p class="text-base text-navy-500 leading-tight mt-2">
            {{ location.need }}
            </p>
...

我尝试使用与此类似的方法,但无法弄清楚: 我假设我需要一种方法来搜索和替换字符串中的单词...

methods: {
            highlight() {
                if(!this.query) {
                    return this.content;
                }
                return this.content.replace(new RegExp(this.query, "HOPE"), match => {
                    return '<span class="highlightText">' + match + '</span>';
                });
            }

任何帮助将不胜感激。

【问题讨论】:

  • 我想我已经回答了类似here 的问题。这能解决你的问题吗?
  • @DavidWeldon 感谢您的链接。我还没有弄清楚,但看起来我在正确的轨道上。

标签: vue.js


【解决方案1】:

为了达到预期的效果,使用下面的选项创建下面的高亮方法

  1. 在循环内创建了高亮方法
  2. 查词索引-HOPE
  3. 使用 v-html 来使用该变量

    methods: { highlight: function(val) { if(val.indexOf('HOPE') !== -1){ return val.replace("HOPE", 'HOPE');
    } return ''+val+''

    } }

工作代码供参考:

var app = new Vue({
  el: '#app',
  data:  function() {
        return {
            locations: [{
                    id: 1,
                    name: 'Example',
                    need: "Lorem ipsum HOPE dolor sit amet.",
                },
                {
                    id: 2,
                    name: 'Example 2',
                    need: "Morbi et lobortis ante, HOPE eu viverra quam.",

                },

              ]
            }
    },
  methods: {
     highlight: function(val) {
       if(val.indexOf('HOPE') !== -1){
        return val.replace("HOPE", '<span class="highlightText">HOPE</span>');       
       }
       return '<span>'+val+'</span>'

  }
  }
})
.highlightText{
  background: red
}
<div>
  <div id="app">
    <div v-for="(location, index) in locations">
            <p class="text-base text-navy-500 leading-tight mt-2">
           
              <div v-html="highlight(location.need)"></div>
            </p>
  </div>
<div>

codepen - https://codepen.io/nagasai/pen/WNegWXx

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 2019-11-30
    • 2011-12-23
    • 2022-01-15
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多