重叠的 Vue 组件
Overlapping Vue components
我有这样的字符串:
"Hello World! It's me, Chelsea."
和一个字符串列表。
["Hello", "World", "Chelsea"]
我想在 Vue 组件中动态包装匹配的字符串。单独来看,它看起来像这样:
<MyComponent :text="Hello"/> <MyComponent :text="World"/>! It's me, <MyComponent :text="Chelsea"/>.
解决方案可能如下所示(感谢 Ulysse BN):
<template v-for="s in string.split(/\b/)">
<MyComponent v-if="list.includes(s)" :string="s"/>
<span v-else>{{ s }}</span>
</template>
但是我们 运行 遇到的问题是我们的列表中有多个单词字符串(例如 "It's me"),更具体地说,是重叠的单词。如果我们添加到字符串列表 "Hello World",理想结果如下所示:
<MyComponent :text="Hello World">
<MyComponent :text="Hello"/>
<MyComponent :text="World"/>!
</MyComponent>
It's me, <MyComponent :text="Chelsea"/>.
我怎样才能实现这个功能?我有预感它涉及v-for和某种递归函数,但我不能说。
我不确定你的用例,但也许像这样的东西会合适:
<template v-for="item in myContent">
<span v-if="item.type === 'string'">{{ item.content }}</span>
<my-component v-else-if="item.type === 'component'" :text="item.content" />
</template>
myContent: [
{'content': 'hello', type: 'string'},
{'content': 'hello world', type: 'component'},
{'content: 'world', type: 'component'},
{'content': 'oh hello world', type: 'string'}
]
您使用 computed 获取字符串,return 在此结构中,拆分任何匹配的词。
我有这样的字符串:
"Hello World! It's me, Chelsea."
和一个字符串列表。
["Hello", "World", "Chelsea"]
我想在 Vue 组件中动态包装匹配的字符串。单独来看,它看起来像这样:
<MyComponent :text="Hello"/> <MyComponent :text="World"/>! It's me, <MyComponent :text="Chelsea"/>.
解决方案可能如下所示(感谢 Ulysse BN):
<template v-for="s in string.split(/\b/)">
<MyComponent v-if="list.includes(s)" :string="s"/>
<span v-else>{{ s }}</span>
</template>
但是我们 运行 遇到的问题是我们的列表中有多个单词字符串(例如 "It's me"),更具体地说,是重叠的单词。如果我们添加到字符串列表 "Hello World",理想结果如下所示:
<MyComponent :text="Hello World">
<MyComponent :text="Hello"/>
<MyComponent :text="World"/>!
</MyComponent>
It's me, <MyComponent :text="Chelsea"/>.
我怎样才能实现这个功能?我有预感它涉及v-for和某种递归函数,但我不能说。
我不确定你的用例,但也许像这样的东西会合适:
<template v-for="item in myContent">
<span v-if="item.type === 'string'">{{ item.content }}</span>
<my-component v-else-if="item.type === 'component'" :text="item.content" />
</template>
myContent: [
{'content': 'hello', type: 'string'},
{'content': 'hello world', type: 'component'},
{'content: 'world', type: 'component'},
{'content': 'oh hello world', type: 'string'}
]
您使用 computed 获取字符串,return 在此结构中,拆分任何匹配的词。