写个函数式组件KeywordText,放在组件目录/src/components下
<script>
export default {
name: 'KeywordText',
props: {
keyword: {
type: String,
default: ''
},
text: {
type: String,
required: true
}
},
render (h) {
const vnodes = []
const text = this.text.split(this.keyword)
text.forEach(str => {
vnodes.push(h('span', null, str))
vnodes.push(h('span', { style: 'color: #007dff;' }, this.keyword))
})
if (text.length > 0) {
vnodes.pop()
}
return h('span', null, vnodes)
}
}
</script>
引入并使用
<div class="title">
<KeywordText :text="item.name" :keyword="userName" />
</div>
<script>
import KeywordText from '@/components/KeywordText.vue'
export default {
data () {
return {
userName: '关键字'
}
}
components: { KeywordText }
}
</script>```