vue3 setup中defineEmits与defineProps的使用案例

news/2024/7/10 1:07:40 标签: vue.js, javascript, 前端, typescript, vue

目录

一、defineEmits的使用

二、 defineProps的使用

总结


一、defineEmits的使用

使用说明
1、在子组件中调用defineEmits并定义要发射给父组件的方法

const emits = defineEmits(['foldChange'])

2、使用defineEmits会返回一个方法,使用一个变量emits(变量名随意)去接收

3、在子组件要触发的方法中,调用emits并传入发射给父组件的方法以及参数

 emits('foldChange', isFold.value)

1.子组件定义:

<template>
  <div class="nav-header">
    <el-icon size="25" class="fold-menu" @click="handleFoldClick">
      <component :is="`${isFold ? 'Fold' : 'Expand'}`"></component>
    </el-icon>
    <!-- <el-icon><Fold /></el-icon> -->
    <!-- <Expand -->
  </div>
</template>

<script setup lang="ts">

import { ref, defineEmits } from 'vue'

// 定义发射给父组件的方法
const emits = defineEmits(['foldChange'])

const isFold = ref(false)

const handleFoldClick = () => {
  isFold.value = !isFold.value
  emits('foldChange', isFold.value)
}

</script>

2.父组件接收使用:

<template>
  <div class="main">
    <el-container class="main-content">
      <el-aside :width="isCollapse ? '60px' : '210px'">
        <nav-menu :collapse="isCollapse"></nav-menu>
      </el-aside>
      <el-container class="page">
        <el-header class="page-header">
          <nav-header @foldChange="handleFoldChange"></nav-header>
        </el-header>
        <el-main class="page-content">Main</el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>

import NavMenu from '@/components/nav-menu'
import NavHeader from '@/components/nav-header'
import { ref } from 'vue'


const isCollapse = ref(false)

const handleFoldChange = (isFold: boolean) => {
  isCollapse.value = isFold
}

</script>

二、 defineProps的使用

使用说明
1、在父组件中定义String、Number、Boolean、Array、Object、Date、Function、Symbol这些类型的数据
2、在子组件中通过defineProps API来进行接受
3、通过子组件事件修改变量值,同时将值传递给父组件,对父组件的变量进行赋值
4、向子组件传递非props的属性,用法及效果如下
 

1.1  子组件定义 方式一

<template>
    <h3 v-bind="$attrs">字符串: {{props.str}}</h3>
    <h3>数字: {{props.num}}</h3>
    <h3>布尔: {{props.bool}}</h3>
    <h3>数组: {{props.arr}}</h3>
    <h3>对象: {{props.obj}}</h3>
    <h3>日期: {{props.date}}</h3>
    <h3>Symbol: {{props.a}} - {{props.b}}</h3>
</template>
<script setup>
    import { defineProps } from 'vue'
    const props = defineProps({
        str: String,
        num: Number,
        bool: Boolean,
        arr: Array,
        obj: Object,
        date: Date,
        getConsole: Function,
        message: Object,
        a: Symbol,
        b: Symbol
    })
    
    props.getConsole()
</script>

1.2  子组件定义 方式二

<template>
    <div class="shopList">
        <div class="shopContent" 
        :class="{tabActive: currentIndex === index }"
        v-for="(tab, index) in tabBars" :key="index"
        @click="itemClick(index)">
            {{tab.name}}
        </div>
    </div>
</template>
<script  setup>
    import { defineProps,ref,defineEmits } from 'vue'
    // 接受父组件传递的数据
    const props = defineProps({
        tabBar: {
            type: Array,
            default: () => []
        }
    })

    // 定义属性
    const currentIndex = ref(0)
    const tabBars = JSON.parse(JSON.stringify(props.tabBar))


    // 定义发射给父组件的方法
    const emits = defineEmits(['tabClick'])

    // tab点击的方法
    const itemClick = (e) => {
        currentIndex.value = e
        emits('tabClick', currentIndex.value)
    }
</script>
<style lang="scss" scoped>
.shopList {
    display: flex;
    justify-content: center;
    align-items: center;
    .shopContent {
        flex: 1;
        text-align: center;
        padding: 20px;
        cursor: pointer;
    }
    .tabActive {
        border-bottom: 3px solid #bf0706;
        color: #bf0706;
    }
}
</style>

2、父组件使用 

javascript"><template>
        <showMessage
            :str="str"
            :num="num"
            :bool="bool"
            :arr="arr"
            :obj="obj"
            :date="date"
            :a = "a"
            :b="b"
            :getConsole="getConsole"
            id="abc"
            class="bcd"
        ></showMessage>
</template>
<script  setup>
import showMessage from './ShowMessage.vue'


    // 定义属性
    const str = '吃饭、睡觉、敲代码'
    const num =  100
    const bool = true
    const arr = ['apple', 'lemon', 'orange']
    const obj = {
                name: 'coderXiao',
                age: 18
            }
    const date = new Date()
    const a = Symbol('好好学习')
    const b = Symbol('天天向上')

    // 定义方法
    const getConsole = () => {
         console.log('传递给子组件的方法');
    }
</script>
<style lang="scss" scoped>
 
</style>

总结

好记性不如烂笔头,放了国庆八天假回来,看着代码好陌生...


http://www.niftyadmin.cn/n/5078134.html

相关文章

电子沙盘数字沙盘大数据人工智能开发教程第16课

电子沙盘数字沙盘大数据可视化GIS系统开发教程第16课&#xff1a;新增加属性在MTGIS3d控件 public bool ShowFLGrid;//是否显 示方里网格。 public bool Atmosphere;//是否显示大气圈。&#xff08;因为WPF不支持shader功能&#xff0c;所以效果嘛。。。&#xff09; 在SDK中为…

pymoo包NSGA2算法实现多目标遗传算法调参详细说明

pymoo包NSGA2算法实现多目标遗传算法调参详细说明 1.定义待求解问题1.0定义问题的参数说明1.0.0 求解问题必须设置在def _evaluate(self, x, out, *args, **kwargs)函数中1.0.1 问题必须用 out["F"] [f1, f2] 包裹起来1.0.2 约束条件也必须用 out["G"] […

XLSX json转文本流 json转文件

封装一个公共 xlsx.js import { read, utils, writeFile } from xlsx // 文本流转json // 入参&#xff1a;文本流 回调 入参{} export const readJsonFromFile (file, callBackFn, opt) > {const reader new FileReader()reader.readAsArrayBuffer(file)reader.onload …

FreeRTOS学习笔记(一)

一、基础知识思维导图 vtaskdelay函数会开启中断&#xff0c;所以在临界区不能用vtaskdelay 二、任务的创建与删除 2.1、任务的动态创建与删除 ........#define START_TASK_PRIO 1 #define START_TASK_STACK_SIZE 128 TaskHandle_t start_task_handler; void …

flink以增量+全量的方式更新广播状态

背景 flink在实现本地内存和db同步配置表信息时&#xff0c;想要做到类似于增量(保证实时性) 全量(保证和DB数据一致)的效果&#xff0c;那么我们如何通过flink的广播状态外部定时器定时全量同步的方式来实现呢&#xff1f; 实现增量全量的效果 package wikiedits.schedule…

hive 知识总结

​编辑 社区公告教程下载分享问答JD 登 录 注册 01 hive 介绍与安装 1 hive介绍与原理分析 Hive是一个基于Hadoop的开源数据仓库工具&#xff0c;用于存储和处理海量结构化数据。它是Facebook 2008年8月开源的一个数据仓库框架&#xff0c;提供了类似于SQL语法的HQL&#xf…

单目标应用:遗传算法(Genetic Algorithm,GA)求解微电网优化MATLAB

一、微网系统运行优化模型 微电网优化模型介绍&#xff1a; 微电网多目标优化调度模型简介_IT猿手的博客-CSDN博客 二、遗传算法GA 遗传算法&#xff08;Genetic Algorithm&#xff0c;GA&#xff09;起源于对生物系统所进行的计算机模拟研究&#xff0c;是一种随机全局搜索…

B端企业如何通过软文提升品牌影响力?

生活中我们采购某种商品时总会考虑这类商品行业类的知名品牌&#xff0c;这就是品牌影响力的重要性&#xff0c;B端企业也需要品牌影响力&#xff0c;由于B端企业的特殊性&#xff0c;它更需要通过口碑和声誉的提升增强用户信任。软文就能帮助企业提升品牌影响力&#xff0c;下…