vue3父组件向子组件传值,异步数据,子组件需要监听才能取到
vue3父组件传值到子组件,异步请求数据需要监听参数
·
父组件
<script setup>
import { ref } from "vue";
import getPosts from "../composibles/getPosts";
import PostList from "../components/PostList.vue";
import Spinner from "../components/Spinner.vue";
import TagCloud from "../components/TagCloud.vue";
const {posts,load}=getPosts();
load();
</script>
<template>
<div class="home">
<div v-if="posts" class="layout">
<PostList :posts="posts" />
<TagCloud :posts="posts" v-if="posts!=null"/>
</div>
<div v-else>
<Spinner/>
</div>
</div>
</template>
<style scoped>
.home{
max-width: 1200px;
margin:0 auto;
padding:10px;
}
.layout{
display: grid;
grid-template-columns: 3fr 1fr;
gap:20px;
}
</style>
子组件
<script setup>
import { ref,watch} from "vue";
const tags=ref([]);
const tagSet=new Set();
const props = defineProps({
posts:Array,
});
watch(
() => props.posts,
(val, prevVal) => {
val.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="{name:'Tag',params:{tag:tag}}">#{{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>
更多推荐
已为社区贡献2条内容
所有评论(0)