在Vuejs的列表对象中设置文本样式的一部分 [英] style part of the text within a list object in Vuejs

查看:244
本文介绍了在Vuejs的列表对象中设置文本样式的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了多种方法在vuejs中使用计算,监视和方法属性来对数据对象的一部分进行样式设置.我仍然不知道如何做才能使健康!"中的健康"一词成为可能.串成不同的风格.

I try many way to style part of the data object using computed, watch, and method property in vuejs. I still have no clue what can I do to make just the "healthy" word within the 'It is healthy!' string into different style.

<template>
   <div='container'>
      <div v-for="item in food">
        {{ item }}
      </div>
   </div>
</template>
<script>
  export default{
   data(){
     return{
        food: [
           { name: 'fish', message: 'It is great!'},
           { name: 'carrot', message: 'It is healthy!'},
        ],
      }
   }
}
</script>

推荐答案

下面是一个有效的示例,该示例使用方法来拆分每条消息并确定是否应突出显示该消息:

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>

以上内容演示了完成此操作的一种简单方法-您可能会发现失败的特殊情况.您可以想象words的一个更复杂的版本,该版本提取带有和不带有健康"一词的子字符串列表.这样会产生更浅的HTML结构.

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.

这篇关于在Vuejs的列表对象中设置文本样式的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆