我尝试了多种方法使用 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/