父组件的代码:index.Vue
<template>
<div class="info">
<div class="info-left">
<Left
:contentList="contentList"
:total="total"
:page="page"
:size="size"
@changePages="changePages"
@changeSize="changeSize"
></Left>
</div>
<div class="info-right">
<Right :hotList="hotList"></Right>
</div>
</div>
</div>
</template>
<script lang='ts' setup>
import Left from './Left.vue'
import Right from './Right.vue'
const contentList = ref<any[]>([])
const hotList = ref<any[]>([])
const total = ref(0)
const size = 5
const page = ref<any>(1)
const changePages = (pages:any) => {
page.value = pages
load("")
}
const load = async(type:any){
let getList = await getTecher({
page: page.value,
pageSize: size,
articleType: 'Li'
})
contentList.value = getList .list
total.value = getList .total
}
const getHotList = async (moudleName: string) => {
let hot = await getHot(4)
hotList.value = hot
}
</script>
子组件 Left.vue
<template>
<div class="pagination">
<n-pagination
v-model="props.page"
:item-count="total"
show-quick-jumper
style="justify-content: center"
:on-update:page="showPageChange"
/>
</div>
</template>
<script lang = 'ts' setup>
import { defineProps,defineEmits } from 'vue'
const props = defineProps({
contentList: Array,
total: Number,
page: Number,
size: Number
})
// 计算总页数
const emits = defineEmits(['changePages'])
const showPageChange = (page: number) => {
emits('changePages', page)
}
</script>
子组件 Right.vue
<template>
<div>
<span v-if="hotList.length <= 0">暂无数据</span>
<ul v-else class="keynote">
<li
v-for="(item, index) in hotList"
:key="index"
class="keys"
@click="handleOpenDetail(item)"
>
<p class="note">{{ item.title }}</p>
<p class="k_date">{{ item.createTime.slice(5, 10) }}</p>
</li>
</ul>
</div>
</template>
<script lang= 'ts' setup>
import { defineProps } from 'vue'
const props = defineProps({
hotList: Array
})
</script>
一、父传子 defineProps
父组件index.vue中在调用子组件Left.vue和Right.vue时,使用v-bind绑定参数contentList,total,page,size以及hotList,在子组件Left.vue中,就使用了defineProps接受那些参数,可以试着打印props,结果如下:
console.log(props,73737373);
console.log(props.contentList);
console.log(props.total);
console.log(props.page);
console.log(props.size);
之后就可以正常使用该参数了
二、子传父defineEmits
子组件传值给父组件主要是子组件通过defineEmits注册一个自定义事件,而后触发emit去调用该自定义事件,并产地参数给父组件。
在父组件中调用子组件时,通过v-on绑定一个函数,通过该函数获取传过来的值。
看上边的父组件index.vue中调用Left.vue这个子组件时,当子组件Left.vue需要传参给父组件index.vue时,使用defineEmits注册一个事件changePages,而后设置点击事件showPageChange去触发emit,去调用我们注册的自定义事件changePages,并传递page参数至父组件。
父组件index.vue在获取子组件Left.vue传过来的值时,通过在子组件上使用v-on设置响应函数changePages (该函数与子组件中的注册自定义事件changePages名称需一致)