vue3 子传父
Posted Power
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue3 子传父相关的知识,希望对你有一定的参考价值。
父组件
<template>
<div class="news-component">
<p class="title">新闻页</p>
<div class="news-detail-content">
子组件:
<news-detail :newList="newList" @addNew="receiveAddNew" @delet="receiveDeleteNew"></news-detail>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive } from \'vue\';
import NewsDetail from \'@/components/newDetail.vue\';// 引入子组件
export default defineComponent({
name: \'News\',
components: {
\'news-detail\': NewsDetail,
},
setup(props) {
// 创建一个响应式的新闻列表
const newList = reactive([
{ title: \'新闻1\', id: \'xw1\' },
{ title: \'新闻2\', id: \'xw2\' },
{ title: \'新闻3\', id: \'xw3\' },
]);
return {
newList,
};
},
methods: {
/**
* 接收(子组件)新增新闻数据
* @param value 新增的新闻数据对象
*/
receiveAddNew(value: any) {
this.newList.push(value);
},
/**
* 接收(子组件)删除新闻数据
* @param index 被删除新闻的下标
*/
receiveDeleteNew(index: number) {
this.newList.splice(index, 1);
},
},
});
</script>
<style lang="less" scoped>
@import \'@/assets/css/variable.less\';
.news-component {
width: 100%;
height: 100%;
.title {
font-size: 40px;
text-align: center;
}
.news-detail-content {
width: 90%;
height: 80%;
margin: 0 auto;
}
}
</style>
子组件
<template>
<div class="news-component">
<p>新闻详情组件</p>
<br />
渲染父组件传过来的数据:
<p class="item-new"
v-for="(item, index) in newList"
:key="item.id">
{{ item.title }}---{{ item.id }}
<van-button type="warning" @click="deletNews(index)"> 删除 </van-button>
</p>
<br />
<van-button type="info" @click="addNews">添加一条新闻</van-button>
</div>
</template>
<script lang="ts">
import { defineComponent } from \'vue\';
export default defineComponent({
name: \'NewsDetail\',
props: [\'newList\'],
setup(props, { emit }) {
let addNews = () => {
emit(\'addNew\', { title: `新闻${props.newList.length + 1}`, id: `xw${props.newList.length + 1}` });
};
let deletNews = (index: number) => {
emit(\'delet\', index);
};
return {
addNews,
deletNews,
};
}
});
</script>
<style lang="less" scoped>
@import \'@/assets/css/variable.less\';
.news-component {
width: 100%;
height: 100%;
background: rgba(201, 194, 194, 0.6);
font-size: @default-fontSize;
overflow: auto;
.item-new {
margin: 20px 0;
}
}
</style>
以上是关于vue3 子传父的主要内容,如果未能解决你的问题,请参考以下文章