[Vuejs]-Style part of the text within a list object in Vuejs

2đź‘Ť

âś…

Here’s a working example using methods to split each message and determine if it should be highlighted:

<template>
  <div class="container">
    <div v-for="(value, name) in food" :key="name">
      <span v-for="(word, index) in words(value)" :key="index">
        <span v-if="isHealthy(word)" class="healthy">{{ word }} </span>
        <span v-else>{{ word }} </span>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      food: { fish: 'It is great!', carrot: 'It is healthy!' },
    };
  },
  methods: {
    words(string) {
      return string.split(/\s+/);
    },
    isHealthy(string) {
      return /healthy/i.test(string);
    },
  },
};
</script>

<style scoped>
.healthy {
  color: red;
}
</style>

The above demonstrates a simple way to accomplish this – you may find corner cases where it fails. You could imagine a more complex version of words which extracts a list of sub-strings both with and without the word “healthy”. That would produce a more shallow HTML structure.

👤David Weldon

2đź‘Ť

I created CodePen example:

Codepen

HTML:

<div id="app">
  <div>
    <div v-for="(value, name) in food" v-key="name">
      {{ name }}: <span v-html="isHealthy(value)"></span>
    </div>
  </div>
</div>

CSS:

.healthy {
  color: green;
  font-weight: 700;
}

JS:

new Vue({
  el: "#app",
  data: () => ({
    food: { fish: 'It is great!', carrot: 'It is healthy!' }
  }),
  methods: {
    isHealthy(str) {
      if(str.includes("healthy")) {
        return str.replace("healthy", "<span class='healthy'>healthy</span>");
      }
      return str;
    }
  }
});

👤patonjo

2đź‘Ť

Essentially you need to add some kind of identifying class on the word “healthy”.
This requires modifying the original food data. You can use computed to generate a new highlightedFood data, that replaces “healthy” with a <span class="highlight">healthy</span>. You can simply style that however you want in the style tag.

<template>
  <div id="app">
    <div v-for="(item, index) in highlightedFood" :key="index">
      <div v-html="item"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      food: [
        { name: "fish", message: "It is great!" },
        { name: "carrot", message: "It is healthy!" }
      ]
    };
  },
  computed: {
    highlightedFood() {
      return this.food.map(item => {
        return {
          name: item.name,
          message: item.message.replace(
            "healthy",
            "<span class='highlight'>healthy</span>"
          )
        };
      });
    }
  }
};
</script>

<style>
.highlight {
  color: green;
}
</style>

Note, if you use scoped CSS, you’ll have to use the deep combinator:

<style scoped>
#app >>> .highlight {
  color: green;
}
</style>

More info on deep selectors: https://vue-loader.vuejs.org/guide/scoped-css.html#deep-selectors

👤wrahim

Leave a comment