关于vue.js:vue3-子传父

45次阅读

共计 1822 个字符,预计需要花费 5 分钟才能阅读完成。

父组件

<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>

正文完
 0