在这种情况下,我总是建议使用计算属性。它使您的模板保持干净,并允许在准备数据时有很大的自由。由于它是一个计算属性,所以如果要更改数据,它将自动重新计算。
第一部分是用您需要的所有必要部分创建一些对象:
computed: {
anchors () {
if (!this.posts) {
return [];
}
return this.posts.map(
identifier => {
const [anchor, text] = identifier.split(':', 2);
return {
anchor,
text
}
}
)
}
}
然后在你需要的地方摧毁它。我还为您的V-for添加了一个键,假设第一部分保证是唯一的。如果你的锚能工作的话就需要了。
<template>
<div>
<v-for="{ anchor, text } in anchors" :key="anchor">
<li><a :href="`#${anchor}`">{{ anchor }}</a>:{{ text }}</li>
</v-for>
</div>
</template>
当然,如果需要,可以在链接上使用过滤器,如果需要,可以使用li主体。