在components文件夹下创建一个TagCloud.vue的组件,如下:
- <script setup>
- import { ref } from "vue";
-
- const tags=ref([]);
- const tagArray=[];
- const props = defineProps({
- posts:Array,
- });
- props.posts.forEach ((item)=>{
- item.tags.forEach((tag)=>
- tagArray.push(tag)
- )
- });
- tags.value=tagArray;
-
- script>
-
- <template>
- <div>{{tags}}div>
- template>
-
- <style scoped>
- style>
这样创建的tags中没有去除重复的标签,咱们进行去重, 代码如下:
- <script setup>
- import { ref } from "vue";
-
- const tags=ref([]);
- const tagSet=new Set();
- const props = defineProps({
- posts:Array,
- });
- props.posts.forEach ((item)=>{
- item.tags.forEach((tag)=>
- tagSet.add(tag)
- )
- });
- tags.value=[...tagSet];
-
- script>
-
- <template>
- <div>{{tags}}div>
- template>
-
- <style scoped>
- style>
这样就没有重复的元素了。
可以加点样式,再美化一下页面:
- <script setup>
- import { ref } from "vue";
-
- const tags=ref([]);
- const tagSet=new Set();
- const props = defineProps({
- posts:Array,
- });
- console.log(props.posts);
- alert(props.posts.length);
- props.posts.forEach((item)=>{
- item.tags.forEach((tag)=>
- tagSet.add(tag)
- )
- });
- tags.value=[...tagSet];
-
- script>
-
- <template>
- <div class="tag-cloud">
- <h3>标签h3>
- <div v-for="tag in tags" :key="tag">
- <router-link to="/">#{{tag}}router-link>
- div>
- div>
- template>
-
- <style scoped>
- .tag-cloud{
- padding:10px;
- }
- .tag-cloud h3{
- border-bottom:1px solid #eee;
- padding:16px 8px;
- color:#444;
- }
- .tag-cloud div{
- display: inline-block;
- padding:10px;
-
- }
- .tag-cloud a{
- color:#ccc;
- text-decoration: none;
- }
- style>