javascript - Vuejs 中列表对象中文本部分的样式

标签 javascript vue.js listobject

我尝试了多种方法使用 vuejs 中的计算、监视和方法属性来设置数据对象部分的样式。我仍然不知道如何才能在“它是健康的!”中添加“健康”一词。串成不同的风格。

<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>

最佳答案

这是一个使用方法来拆分每条消息并确定是否应突出显示它的工作示例:

<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 版本,它提取包含和不包含“healthy”一词的子字符串列表。这将产生更浅的 HTML 结构。

关于javascript - Vuejs 中列表对象中文本部分的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56674732/

相关文章:

javascript - 如何将带有双引号反斜杠的 JSON 字符串转换为 Javascript 对象

javascript - 遍历 jquery data() 对象并将它们推送到另一个 data() 对象(数组)中

vue.js - 如何使用 vuex 从命名空间模块访问 getter?

vue.js - v-data-table 错误无法使用远程数据创建属性 isRootInsert

arrays - VBA循环填充数组

excel - 过滤列表时 ListRows.Add() 给出错误

javascript - 具有警报结果的不同代码。

php - 根据条件将 javascript 写入页面

vue.js - 禁用提交按钮,但有效的表单数据不会启用它(vee-validate)

excel - vba 获取表格中特定单元格的范围(listobject)